repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/driver/ioctl.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 dispatch_ioctl(libusb_device_t *dev, IRP *irp)
{
int ret = 0;
NTSTATUS status = STATUS_SUCCESS;
IO_STACK_LOCATION *stack_location = IoGetCurrentIrpStackLocation(irp);
ULONG control_code =
stack_location->Parameters.DeviceIoControl.IoControlCode;
ULONG input_buffer_length
= stack_location->Parameters.DeviceIoControl.InputBufferLength;
ULONG output_buffer_length
= stack_location->Parameters.DeviceIoControl.OutputBufferLength;
ULONG transfer_buffer_length
= stack_location->Parameters.DeviceIoControl.OutputBufferLength;
libusb_request *request = (libusb_request *)irp->AssociatedIrp.SystemBuffer;
char *output_buffer = (char *)irp->AssociatedIrp.SystemBuffer;
char *input_buffer = (char *)irp->AssociatedIrp.SystemBuffer;
MDL *transfer_buffer_mdl = irp->MdlAddress;
status = remove_lock_acquire(dev);
if(!NT_SUCCESS(status))
{
status = complete_irp(irp, status, 0);
remove_lock_release(dev);
return status;
}
if(!request || input_buffer_length < sizeof(libusb_request)
|| input_buffer_length > LIBUSB_MAX_READ_WRITE
|| output_buffer_length > LIBUSB_MAX_READ_WRITE
|| transfer_buffer_length > LIBUSB_MAX_READ_WRITE)
{
DEBUG_ERROR("dispatch_ioctl(): invalid input or output buffer\n");
status = complete_irp(irp, STATUS_INVALID_PARAMETER, 0);
remove_lock_release(dev);
return status;
}
DEBUG_PRINT_NL();
switch(control_code)
{
case LIBUSB_IOCTL_SET_CONFIGURATION:
status = set_configuration(dev, request->configuration.configuration,
request->timeout);
break;
case LIBUSB_IOCTL_GET_CONFIGURATION:
if(!output_buffer || output_buffer_length < 1)
{
DEBUG_ERROR("dispatch_ioctl(), get_configuration: invalid output "
"buffer");
status = STATUS_INVALID_PARAMETER;
break;
}
status = get_configuration(dev, output_buffer, &ret, request->timeout);
break;
case LIBUSB_IOCTL_SET_INTERFACE:
status = set_interface(dev, request->interface.interface,
request->interface.altsetting, request->timeout);
break;
case LIBUSB_IOCTL_GET_INTERFACE:
if(!output_buffer || output_buffer_length < 1)
{
DEBUG_ERROR("dispatch_ioctl(), get_interface: invalid output "
"buffer");
status = STATUS_INVALID_PARAMETER;
break;
}
status = get_interface(dev, request->interface.interface,
output_buffer, &ret, request->timeout);
break;
case LIBUSB_IOCTL_SET_FEATURE:
status = set_feature(dev, request->feature.recipient,
request->feature.index, request->feature.feature,
request->timeout);
break;
case LIBUSB_IOCTL_CLEAR_FEATURE:
status = clear_feature(dev, request->feature.recipient,
request->feature.index, request->feature.feature,
request->timeout);
break;
case LIBUSB_IOCTL_GET_STATUS:
if(!output_buffer || output_buffer_length < 2)
{
DEBUG_ERROR("dispatch_ioctl(), get_status: invalid output buffer");
status = STATUS_INVALID_PARAMETER;
break;
}
status = get_status(dev, request->status.recipient,
request->status.index, output_buffer,
&ret, request->timeout);
break;
case LIBUSB_IOCTL_SET_DESCRIPTOR:
if(input_buffer_length <= sizeof(libusb_request))
{
DEBUG_ERROR("dispatch_ioctl(), set_descriptor: invalid input "
"buffer");
status = STATUS_INVALID_PARAMETER;
break;
}
status = set_descriptor(dev,
input_buffer + sizeof(libusb_request),
input_buffer_length - sizeof(libusb_request),
request->descriptor.type,
request->descriptor.recipient,
request->descriptor.index,
request->descriptor.language_id,
&ret, request->timeout);
break;
case LIBUSB_IOCTL_GET_DESCRIPTOR:
if(!output_buffer || !output_buffer_length)
{
DEBUG_ERROR("dispatch_ioctl(), get_descriptor: invalid output "
"buffer");
status = STATUS_INVALID_PARAMETER;
break;
}
status = get_descriptor(dev, output_buffer,
output_buffer_length,
request->descriptor.type,
request->descriptor.recipient,
request->descriptor.index,
request->descriptor.language_id,
&ret, request->timeout);
break;
case LIBUSB_IOCTL_INTERRUPT_OR_BULK_READ:
if(!transfer_buffer_mdl)
{
DEBUG_ERROR("dispatch_ioctl(), bulk_int_read: invalid transfer "
"buffer");
status = STATUS_INVALID_PARAMETER;
break;
}
return transfer(dev, irp,
USBD_TRANSFER_DIRECTION_IN,
URB_FUNCTION_BULK_OR_INTERRUPT_TRANSFER,
request->endpoint.endpoint,
request->endpoint.packet_size,
transfer_buffer_mdl,
transfer_buffer_length);
case LIBUSB_IOCTL_INTERRUPT_OR_BULK_WRITE:
/* we don't check 'transfer_buffer_mdl' here because it might be NULL */
/* if the DLL requests to send a zero-length packet */
return transfer(dev, irp,
USBD_TRANSFER_DIRECTION_OUT,
URB_FUNCTION_BULK_OR_INTERRUPT_TRANSFER,
request->endpoint.endpoint,
request->endpoint.packet_size,
transfer_buffer_mdl,
transfer_buffer_length);
case LIBUSB_IOCTL_VENDOR_READ:
if(output_buffer_length && !output_buffer)
{
DEBUG_ERROR("dispatch_ioctl(), vendor_read: invalid output buffer");
status = STATUS_INVALID_PARAMETER;
break;
}
status = vendor_class_request(dev,
request->vendor.type,
request->vendor.recipient,
request->vendor.request,
request->vendor.value,
request->vendor.index,
output_buffer,
output_buffer_length,
USBD_TRANSFER_DIRECTION_IN,
&ret, request->timeout);
break;
case LIBUSB_IOCTL_VENDOR_WRITE:
status =
vendor_class_request(dev,
request->vendor.type,
request->vendor.recipient,
request->vendor.request,
request->vendor.value,
request->vendor.index,
input_buffer_length == sizeof(libusb_request) ?
NULL : input_buffer + sizeof(libusb_request),
input_buffer_length - sizeof(libusb_request),
USBD_TRANSFER_DIRECTION_OUT,
&ret, request->timeout);
break;
case LIBUSB_IOCTL_RESET_ENDPOINT:
status = reset_endpoint(dev, request->endpoint.endpoint,
request->timeout);
break;
case LIBUSB_IOCTL_ABORT_ENDPOINT:
status = abort_endpoint(dev, request->endpoint.endpoint,
request->timeout);
break;
case LIBUSB_IOCTL_RESET_DEVICE:
status = reset_device(dev, request->timeout);
break;
case LIBUSB_IOCTL_SET_DEBUG_LEVEL:
DEBUG_SET_LEVEL(request->debug.level);
break;
case LIBUSB_IOCTL_GET_VERSION:
if(!request || output_buffer_length < sizeof(libusb_request))
{
DEBUG_ERROR("dispatch_ioctl(), get_version: invalid output buffer");
status = STATUS_INVALID_PARAMETER;
break;
}
request->version.major = VERSION_MAJOR;
request->version.minor = VERSION_MINOR;
request->version.micro = VERSION_MICRO;
request->version.nano = VERSION_NANO;
ret = sizeof(libusb_request);
break;
case LIBUSB_IOCTL_CLAIM_INTERFACE:
status = claim_interface(dev, request->interface.interface);
break;
case LIBUSB_IOCTL_RELEASE_INTERFACE:
status = release_interface(dev, request->interface.interface);
break;
case LIBUSB_IOCTL_ISOCHRONOUS_READ:
if(!transfer_buffer_mdl)
{
DEBUG_ERROR("dispatch_ioctl(), isochronous_read: invalid transfer "
"buffer");
status = STATUS_INVALID_PARAMETER;
break;
}
return transfer(dev, irp, USBD_TRANSFER_DIRECTION_IN,
URB_FUNCTION_ISOCH_TRANSFER, request->endpoint.endpoint,
request->endpoint.packet_size, transfer_buffer_mdl,
transfer_buffer_length);
case LIBUSB_IOCTL_ISOCHRONOUS_WRITE:
if(!transfer_buffer_mdl)
{
DEBUG_ERROR("dispatch_ioctl(), isochronous_write: invalid transfer "
"buffer");
status = STATUS_INVALID_PARAMETER;
break;
}
return transfer(dev, irp, USBD_TRANSFER_DIRECTION_OUT,
URB_FUNCTION_ISOCH_TRANSFER, request->endpoint.endpoint,
request->endpoint.packet_size, transfer_buffer_mdl,
transfer_buffer_length);
default:
status = STATUS_INVALID_PARAMETER;
}
status = complete_irp(irp, status, ret);
remove_lock_release(dev);
return status;
}
|
tinyos-io/tinyos-3.x-contrib | antlab-polimi/dpcm_C/dpcmEncodeApp.c | <reponame>tinyos-io/tinyos-3.x-contrib
/**
* @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"
#include "quanttables.h"
#include "dpcm_encoder.h"
#include "dpcm_decoder.h"
#define QUALITY 9
#define BANDWIDTH 225000
#define MAX_INPUT_SIZE 2 << 20
int main(int argc, char **argv)
{
char filename[1024];
uint8_t frame = 0;
int bufShift = 0;
FILE *fd;
uint width, height, depth,i;
unsigned char magic_number[2];
unsigned char input_save[MAX_INPUT_SIZE];
uint is_color=1;
uint name_size=0;
uint current_number;
char short_name[1024];
char *tmp_name = NULL;
if (argc > 2) {
sprintf(filename,argv[1]);
frame = (uint8_t) atoi(argv[2]);
}
else {
printf("USAGE: dpcmEncodeApp.exe (.pgm|.ppm) input_file (uint8_t) frame_number\n");
printf("Max input: %d\n",MAX_INPUT_SIZE);
return -1;
}
char* ext=filename, *tmp;
while ( (tmp=strstr(ext,".")) != NULL )
{
ext=&tmp[1];
}
printf("input file:%s ext:%s\n",filename,ext);
if (strcmp(ext,"pgm")==0)
{
is_color=0;
bufShift=1;
}
else
{
is_color=1;
bufShift=3;
}
if (!(fd = fopen(filename, "r")) ){
printf("Can't open data: %s\n", filename);
return -1;
}
// reads magic number
fgets((char *)magic_number,3,fd);
if (strcmp((const char *)magic_number, "P5") == 0 || strcmp((const char *)magic_number, "P6") == 0) {
printf("File already in binary format (Magic number = %s)\n", magic_number);
return -1;
}
if (strcmp((const char *)magic_number, "P2") != 0 && strcmp((const char *)magic_number, "P3") != 0) {
printf("Format not valid: magic_number = %s\n", magic_number);
return -1;
}
// reads height width and depth
fscanf(fd,"%d",&width);
fscanf(fd,"%d",&height);
fscanf(fd,"%d",&depth);
unsigned char input[width*height*bufShift];
// read values
i=0;
while( fscanf(fd,"%d",¤t_number)!=EOF)
{
input[i]=(char)current_number;
i++;
}
fclose(fd);
memcpy(input_save, input, sizeof(input));
// extract file name without path
tmp_name = strrchr(filename,'/'); //skip the / char
if (tmp_name == NULL)
tmp_name = filename;
else
tmp_name = tmp_name +1;
strcat(tmp_name,"\0");
name_size = strlen(tmp_name)-4;
strncpy(short_name,tmp_name,name_size);
printf("Name found: %s, name size: %d\n",short_name, name_size);
dpcm_encode(input,width,height,QUALITY,short_name,frame,BANDWIDTH);
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | csm/tos/lib/tossim/SerialPacket.c | <reponame>tinyos-io/tinyos-3.x-contrib<gh_stars>1-10
/*
* "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."
*/
/**
*
* Injecting packets into TOSSIM.
*
* @author <NAME>
* @author <NAME>
* @date July 15 2007
*/
#include <SerialPacket.h>
#include <sim_serial_packet.h>
SerialPacket::SerialPacket() {
msgPtr = sim_serial_packet_allocate();
allocated = 1;
}
SerialPacket::SerialPacket(sim_serial_packet_t* m) {
if (m != NULL) {
msgPtr = m;
allocated = 0;
}
else {
msgPtr = sim_serial_packet_allocate();
allocated = 1;
}
}
SerialPacket::~SerialPacket() {
if (allocated) {
sim_serial_packet_free(msgPtr);
}
}
void SerialPacket::setDestination(int dest) {
sim_serial_packet_set_destination(msgPtr, (uint16_t)dest);
}
int SerialPacket::destination() {
return sim_serial_packet_destination(msgPtr);
}
void SerialPacket::setLength(int len) {
sim_serial_packet_set_length(msgPtr, (uint8_t)len);
}
int SerialPacket::length() {
return sim_serial_packet_length(msgPtr);
}
void SerialPacket::setType(int type) {
sim_serial_packet_set_type(msgPtr, (uint8_t)type);
}
int SerialPacket::type() {
return sim_serial_packet_type(msgPtr);
}
char* SerialPacket::data() {
char* val = (char*)sim_serial_packet_data(msgPtr);
return val;
}
void SerialPacket::setData(char* data, int len) {
len = (len > maxLength())? maxLength():len;
memcpy(sim_serial_packet_data(msgPtr), data, len);
setLength(len);
}
int SerialPacket::maxLength() {
return (int)sim_serial_packet_max_length(msgPtr);
}
sim_serial_packet_t* SerialPacket::getPacket() {
return msgPtr;
}
void SerialPacket::deliver(int node, long long int t) {
sim_serial_packet_deliver(node, msgPtr, t);
}
void SerialPacket::deliverNow(int node) {
deliver(node, 0);
}
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/registry.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 <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __GNUC__
#include <ddk/cfgmgr32.h>
#else
#include <cfgmgr32.h>
#define strlwr(p) _strlwr(p)
#endif
#include "registry.h"
#include "error.h"
#define CLASS_KEY_PATH_NT "SYSTEM\\CurrentControlSet\\Control\\Class\\"
#define CLASS_KEY_PATH_9X "SYSTEM\\CurrentControlSet\\Services\\Class\\"
#define USB_GET_DRIVER_NAME() \
usb_registry_is_nt() ? driver_name_nt : driver_name_9x;
typedef struct _usb_class_key usb_class_key_t;
struct _usb_class_key {
usb_class_key_t *next;
char name[MAX_PATH];
};
static const char *driver_name_nt = "libusb0";
static const char *driver_name_9x = "libusb0.sys";
static const char *default_class_keys_nt[] =
{
/* USB devices */
"{36fc9e60-c465-11cf-8056-444553540000}",
/* HID devices */
"{745a17a0-74d3-11d0-b6fe-00a0c90f57da}",
/* Network devices */
"{4d36e972-e325-11ce-bfc1-08002be10318}",
/* Image devices */
"{6bdd1fc6-810f-11d0-bec7-08002be2092f}",
/* Media devices */
"{4d36e96c-e325-11ce-bfc1-08002be10318}",
/* Modem devices */
"{4d36e96d-e325-11ce-bfc1-08002be10318}",
/* SmartCardReader devices*/
"{50dd5230-ba8a-11d1-bf5d-0000f805f530}",
NULL
};
static const char *default_class_keys_9x[] =
{
/* USB devices */
"usb",
/* HID devices */
"hid",
/* Network devices */
"net",
/* Image devices */
"image",
/* Media devices */
"media",
/* Modem devices */
"modem",
NULL
};
static bool_t usb_registry_set_device_state(DWORD state, HDEVINFO dev_info,
SP_DEVINFO_DATA *dev_info_data);
static usb_class_key_t *usb_registry_get_usb_class_keys(void);
static usb_class_key_t *usb_registry_get_all_class_keys(void);
static bool_t usb_registry_add_class_key(usb_class_key_t **head,
const char *key);
static bool_t usb_registry_free_class_keys(usb_class_key_t **head);
bool_t usb_registry_is_nt(void)
{
return GetVersion() < 0x80000000 ? TRUE : FALSE;
}
bool_t usb_registry_get_property(DWORD which, HDEVINFO dev_info,
SP_DEVINFO_DATA *dev_info_data,
char *buf, int size)
{
DWORD reg_type;
DWORD key_type;
DWORD length = size;
char *p = NULL;
char *val_name = NULL;
HKEY reg_key = NULL;
memset(buf, 0, size);
switch(which)
{
case SPDRP_LOWERFILTERS:
val_name = "LowerFilters";
key_type = DIREG_DEV;
break;
case SPDRP_UPPERFILTERS:
val_name = "UpperFilters";
key_type = DIREG_DEV;
break;
case SPDRP_SERVICE:
val_name = "NTMPDriver";
key_type = DIREG_DRV;
break;
case SPDRP_CLASSGUID:
val_name = "ClassGUID";
key_type = DIREG_DEV;
case SPDRP_CLASS:
val_name = "Class";
key_type = DIREG_DEV;
break;
case SPDRP_HARDWAREID:
val_name = "HardwareID";
key_type = DIREG_DEV;
break;
case SPDRP_DEVICEDESC:
val_name = "DeviceDesc";
key_type = DIREG_DEV;
break;
case SPDRP_MFG:
val_name = "Mfg";
key_type = DIREG_DEV;
break;
default:
return FALSE;
}
if(usb_registry_is_nt())
{
if(!SetupDiGetDeviceRegistryProperty(dev_info, dev_info_data, which,
®_type, (BYTE *)buf,
size, &length))
{
return FALSE;
}
if(length <= 2)
{
return FALSE;
}
}
else /* Win9x */
{
reg_key = SetupDiOpenDevRegKey(dev_info, dev_info_data,
DICS_FLAG_GLOBAL,
0, key_type, KEY_ALL_ACCESS);
if(reg_key == INVALID_HANDLE_VALUE)
{
usb_error("usb_registry_get_property(): reading "
"registry key failed");
return FALSE;
}
if(RegQueryValueEx(reg_key, val_name, NULL, ®_type,
(BYTE *)buf, &length) != ERROR_SUCCESS
|| length <= 2)
{
RegCloseKey(reg_key);
return FALSE;
}
RegCloseKey(reg_key);
if(reg_type == REG_MULTI_SZ)
{
p = buf;
while(*p)
{
if(*p == ',')
{
*p = 0;
}
p++;
}
}
}
return TRUE;
}
bool_t usb_registry_set_property(DWORD which, HDEVINFO dev_info,
SP_DEVINFO_DATA *dev_info_data,
char *buf, int size)
{
char *val_name = NULL;
char *p = NULL;
HKEY reg_key;
DWORD reg_type;
switch(which)
{
case SPDRP_LOWERFILTERS:
reg_type = usb_registry_is_nt() ? REG_MULTI_SZ : REG_SZ;
val_name = "LowerFilters";
break;
case SPDRP_UPPERFILTERS:
reg_type = usb_registry_is_nt() ? REG_MULTI_SZ : REG_SZ;
val_name = "UpperFilters";
break;
default:
return 0;
}
if(usb_registry_is_nt())
{
if(size > 2)
{
if(!SetupDiSetDeviceRegistryProperty(dev_info, dev_info_data,
which, (BYTE *)buf, size))
{
usb_error("usb_registry_set_property(): setting "
"property '%s' failed", val_name);
return FALSE;
}
}
else
{
if(!SetupDiSetDeviceRegistryProperty(dev_info, dev_info_data,
which, NULL, 0))
{
usb_error("usb_registry_set_property(): deleting "
"property '%s' failed", val_name);
return FALSE;
}
}
}
else
{
p = buf;
while(*p)
{
if(*p == ',')
{
*p = 0;
}
p += (strlen(p) + 1);
}
reg_key = SetupDiOpenDevRegKey(dev_info, dev_info_data,
DICS_FLAG_GLOBAL,
0, DIREG_DEV, KEY_ALL_ACCESS);
if(reg_key == INVALID_HANDLE_VALUE)
{
usb_error("usb_registry_set_property(): reading "
"registry key failed");
return FALSE;
}
if(size > 3)
{
if(RegSetValueEx(reg_key, val_name, 0, reg_type, (BYTE *)buf,
size) != ERROR_SUCCESS)
{
usb_error("usb_registry_set_property(): setting "
"property '%s' failed", val_name);
RegCloseKey(reg_key);
return FALSE;
}
}
else
{
if(RegDeleteValue(reg_key, val_name) != ERROR_SUCCESS)
{
usb_error("usb_registry_set_property(): deleting "
"property '%s' failed", val_name);
RegCloseKey(reg_key);
return FALSE;
}
}
RegCloseKey(reg_key);
}
return TRUE;
}
bool_t usb_registry_insert_class_filter(void)
{
const char *driver_name;
usb_class_key_t *keys;
usb_class_key_t *key;
char buf[MAX_PATH];
driver_name = USB_GET_DRIVER_NAME();
keys = usb_registry_get_usb_class_keys();
if(!keys)
{
usb_error("usb_registry_insert_filter: unable to retrieve class keys\n");
return FALSE;
}
key = keys;
while(key)
{
if(usb_registry_get_mz_value(key->name, "UpperFilters",
buf, sizeof(buf)))
{
usb_registry_mz_string_lower(buf);
if(usb_registry_mz_string_find(buf, driver_name))
{
key = key->next;
continue;
}
}
usb_registry_mz_string_insert(buf, driver_name);
if(!usb_registry_set_mz_value(key->name, "UpperFilters", buf,
usb_registry_mz_string_size(buf)))
{
usb_error("usb_registry_insert_filter: unable to "
"set registry value\n");
}
key = key->next;
}
usb_registry_free_class_keys(&keys);
return TRUE;
}
bool_t usb_registry_remove_class_filter(void)
{
const char *driver_name;
usb_class_key_t *keys;
usb_class_key_t *key;
char buf[MAX_PATH];
driver_name = USB_GET_DRIVER_NAME();
keys = usb_registry_get_all_class_keys();
if(!keys)
{
usb_error("usb_registry_remove_filter: unable to retrieve class keys\n");
return FALSE;
}
key = keys;
while(key)
{
if(usb_registry_get_mz_value(key->name, "UpperFilters",
buf, sizeof(buf)))
{
usb_registry_mz_string_lower(buf);
if(usb_registry_mz_string_find(buf, driver_name))
{
usb_registry_mz_string_remove(buf, driver_name);
usb_registry_set_mz_value(key->name, "UpperFilters", buf,
usb_registry_mz_string_size(buf));
}
}
key = key->next;
}
usb_registry_free_class_keys(&keys);
return TRUE;
}
bool_t usb_registry_remove_device_filter(void)
{
HDEVINFO dev_info;
SP_DEVINFO_DATA dev_info_data;
int dev_index = 0;
char filters[MAX_PATH];
const char *driver_name;
driver_name = USB_GET_DRIVER_NAME();
dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
dev_index = 0;
dev_info = SetupDiGetClassDevs(NULL, "USB", NULL, DIGCF_ALLCLASSES);
if(dev_info == INVALID_HANDLE_VALUE)
{
usb_error("usb_registry_remove_device_filter(): getting "
"device info set failed");
return FALSE;
}
while(SetupDiEnumDeviceInfo(dev_info, dev_index, &dev_info_data))
{
/* remove libusb as a device upper filter */
if(usb_registry_get_property(SPDRP_UPPERFILTERS, dev_info,
&dev_info_data,
filters, sizeof(filters)))
{
usb_registry_mz_string_lower(filters);
if(usb_registry_mz_string_find(filters, driver_name))
{
int size;
usb_registry_mz_string_remove(filters, driver_name);
size = usb_registry_mz_string_size(filters);
usb_registry_set_property(SPDRP_UPPERFILTERS, dev_info,
&dev_info_data, filters, size);
}
}
/* remove libusb as a device lower filter */
if(usb_registry_get_property(SPDRP_LOWERFILTERS, dev_info,
&dev_info_data,
filters, sizeof(filters)))
{
usb_registry_mz_string_lower(filters);
if(usb_registry_mz_string_find(filters, driver_name))
{
int size;
usb_registry_mz_string_remove(filters, driver_name);
size = usb_registry_mz_string_size(filters);
usb_registry_set_property(SPDRP_LOWERFILTERS, dev_info,
&dev_info_data, filters, size);
}
}
dev_index++;
}
SetupDiDestroyDeviceInfoList(dev_info);
return TRUE;
}
static bool_t usb_registry_set_device_state(DWORD state, HDEVINFO dev_info,
SP_DEVINFO_DATA *dev_info_data)
{
SP_PROPCHANGE_PARAMS prop_params;
memset(&prop_params, 0, sizeof(SP_PROPCHANGE_PARAMS));
prop_params.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
prop_params.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
prop_params.StateChange = state;
prop_params.Scope = DICS_FLAG_CONFIGSPECIFIC;//DICS_FLAG_GLOBAL;
prop_params.HwProfile = 0;
if(!SetupDiSetClassInstallParams(dev_info, dev_info_data,
(SP_CLASSINSTALL_HEADER *)&prop_params,
sizeof(SP_PROPCHANGE_PARAMS)))
{
usb_error("usb_registry_set_device_state(): setting class "
"install parameters failed");
return FALSE;
}
if(!SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, dev_info, dev_info_data))
{
usb_error("usb_registry_set_device_state(): calling class "
"installer failed");
return FALSE;
}
return TRUE;
}
bool_t usb_registry_restart_device(HDEVINFO dev_info,
SP_DEVINFO_DATA *dev_info_data)
{
return usb_registry_set_device_state(DICS_PROPCHANGE, dev_info,
dev_info_data);
}
bool_t usb_registry_stop_device(HDEVINFO dev_info,
SP_DEVINFO_DATA *dev_info_data)
{
return usb_registry_set_device_state(DICS_DISABLE, dev_info,
dev_info_data);
}
bool_t usb_registry_start_device(HDEVINFO dev_info,
SP_DEVINFO_DATA *dev_info_data)
{
return usb_registry_set_device_state(DICS_ENABLE, dev_info,
dev_info_data);
}
bool_t usb_registry_is_service_libusb(HDEVINFO dev_info,
SP_DEVINFO_DATA *dev_info_data)
{
char service_name[MAX_PATH];
if(!usb_registry_get_property(SPDRP_SERVICE, dev_info, dev_info_data,
service_name, sizeof(service_name)))
{
return FALSE;
}
usb_registry_mz_string_lower(service_name);
if(usb_registry_mz_string_find_sub(service_name, "libusb"))
{
return TRUE;
}
return FALSE;
}
void usb_registry_stop_libusb_devices(void)
{
HDEVINFO dev_info;
SP_DEVINFO_DATA dev_info_data;
int dev_index = 0;
dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
dev_index = 0;
dev_info = SetupDiGetClassDevs(NULL, "USB", NULL,
DIGCF_ALLCLASSES | DIGCF_PRESENT);
if(dev_info == INVALID_HANDLE_VALUE)
{
usb_error("usb_registry_stop_libusb_devices(): getting "
"device info set failed");
return;
}
while(SetupDiEnumDeviceInfo(dev_info, dev_index, &dev_info_data))
{
if(usb_registry_is_service_libusb(dev_info, &dev_info_data))
{
usb_registry_stop_device(dev_info, &dev_info_data);
}
dev_index++;
}
SetupDiDestroyDeviceInfoList(dev_info);
}
void usb_registry_start_libusb_devices(void)
{
HDEVINFO dev_info;
SP_DEVINFO_DATA dev_info_data;
int dev_index = 0;
dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
dev_index = 0;
dev_info = SetupDiGetClassDevs(NULL, "USB", NULL,
DIGCF_ALLCLASSES | DIGCF_PRESENT);
if(dev_info == INVALID_HANDLE_VALUE)
{
usb_error("usb_registry_stop_libusb_devices(): getting "
"device info set failed");
return;
}
while(SetupDiEnumDeviceInfo(dev_info, dev_index, &dev_info_data))
{
if(usb_registry_is_service_libusb(dev_info, &dev_info_data))
{
usb_registry_start_device(dev_info, &dev_info_data);
}
dev_index++;
}
SetupDiDestroyDeviceInfoList(dev_info);
}
bool_t usb_registry_match(HDEVINFO dev_info,
SP_DEVINFO_DATA *dev_info_data)
{
char tmp[MAX_PATH];
if(!usb_registry_get_property(SPDRP_HARDWAREID, dev_info, dev_info_data,
tmp, sizeof(tmp)))
{
usb_error("usb_registry_match_no_hubs(): getting hardware id "
"failed");
return FALSE;
}
usb_registry_mz_string_lower(tmp);
/* search for USB devices, skip root hubs and interfaces of composite */
/* devices */
if(usb_registry_mz_string_find_sub(tmp, "&mi_")
|| usb_registry_mz_string_find_sub(tmp, "root_hub"))
{
return FALSE;
}
return TRUE;
}
bool_t usb_registry_get_mz_value(const char *key, const char *value,
char *buf, int size)
{
HKEY reg_key = NULL;
DWORD reg_type;
DWORD reg_length = size;
bool_t ret = FALSE;
char *p;
memset(buf, 0, size);
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_ALL_ACCESS, ®_key)
== ERROR_SUCCESS)
{
if(RegQueryValueEx(reg_key, value, NULL, ®_type,
buf, ®_length) == ERROR_SUCCESS)
{
if(reg_type == REG_SZ)
{
p = buf;
while(*p)
{
if(*p == ',')
{
*p = 0;
}
p++;
}
}
ret = TRUE;
}
}
if(reg_key)
{
RegCloseKey(reg_key);
}
return ret;
}
bool_t usb_registry_set_mz_value(const char *key, const char *value,
char *buf, int size)
{
HKEY reg_key = NULL;
bool_t ret = FALSE;
char *p;
/* convert REG_MULTI_SZ to REG_SZ */
if(!usb_registry_is_nt())
{
p = buf;
while(*p && *(p + 1))
{
if(*p == 0)
{
*p = ',';
}
p++;
}
}
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_ALL_ACCESS, ®_key)
== ERROR_SUCCESS)
{
if(size > 2)
{
if(usb_registry_is_nt())
{
if(RegSetValueEx(reg_key, value, 0, REG_MULTI_SZ, buf, size)
== ERROR_SUCCESS)
{
ret = TRUE;
}
}
else
{
if(RegSetValueEx(reg_key, value, 0, REG_SZ, buf, size)
== ERROR_SUCCESS)
{
ret = TRUE;
}
}
}
else
{
if(RegDeleteValue(reg_key, value) == ERROR_SUCCESS)
{
ret = TRUE;
}
}
}
if(reg_key)
{
RegCloseKey(reg_key);
}
return ret;
}
int usb_registry_mz_string_size(const char *src)
{
char *p = (char *)src;
if(!src)
{
return 0;
}
while(*p)
{
p += (strlen(p) + 1);
}
return (int)(p - src) + 1;
}
char *usb_registry_mz_string_find_sub(const char *src, const char *str)
{
while(*src)
{
if(strstr(src, str))
{
return (char *)src;
}
src += (strlen(src) + 1);
}
return NULL;
}
char *usb_registry_mz_string_find(const char *src, const char *str)
{
while(*src)
{
if(!strcmp(src, str))
{
return (char *)src;
}
src += strlen(src) + 1;
}
return NULL;
}
bool_t usb_registry_mz_string_insert(char *src, const char *str)
{
while(*src)
{
src += (strlen(src) + 1);
}
memcpy(src, str, strlen(str));
src += strlen(str);
*src = 0;
*(src + 1) = 0;
return TRUE;
}
bool_t usb_registry_mz_string_remove(char *src, const char *str)
{
char *p;
bool_t ret = FALSE;
int size;
do {
src = usb_registry_mz_string_find(src, str);
if(!src)
{
break;
}
else
{
ret = TRUE;
}
p = src;
size = 0;
while(*p)
{
p += strlen(p) + 1;
size += strlen(p) + 1;
}
memmove(src, src + strlen(src) + 1, size);
} while(1);
return TRUE;
}
void usb_registry_mz_string_lower(char *src)
{
while(*src)
{
strlwr(src);
src += (strlen(src) + 1);
}
}
bool_t usb_registry_restart_all_devices(void)
{
HDEVINFO dev_info;
SP_DEVINFO_DATA dev_info_data;
int dev_index;
char id[MAX_PATH];
dev_index = 0;
dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
dev_info = SetupDiGetClassDevs(NULL, "USB", NULL,
DIGCF_ALLCLASSES | DIGCF_PRESENT);
if(dev_info == INVALID_HANDLE_VALUE)
{
usb_error("usb_registry_restart_all_devices(): getting "
"device info set failed");
return FALSE;
}
while(SetupDiEnumDeviceInfo(dev_info, dev_index, &dev_info_data))
{
if(!usb_registry_get_property(SPDRP_HARDWAREID, dev_info,
&dev_info_data, id, sizeof(id)))
{
usb_error("usb_registry_restart_all_devices(): getting hardware "
"id failed");
dev_index++;
continue;
}
usb_registry_mz_string_lower(id);
/* restart root hubs */
if(usb_registry_mz_string_find_sub(id, "root_hub"))
{
usb_registry_restart_device(dev_info, &dev_info_data);
}
dev_index++;
}
SetupDiDestroyDeviceInfoList(dev_info);
return TRUE;
}
usb_class_key_t *usb_registry_get_usb_class_keys(void)
{
HDEVINFO dev_info;
SP_DEVINFO_DATA dev_info_data;
int dev_index = 0;
int i;
char class[MAX_PATH];
char tmp[MAX_PATH];
usb_class_key_t *keys = NULL;
DWORD class_property;
const char *class_path;
const char **default_class_keys;
if(usb_registry_is_nt())
{
class_property = SPDRP_CLASSGUID;
class_path = CLASS_KEY_PATH_NT;
default_class_keys = default_class_keys_nt;
}
else
{
class_property = SPDRP_CLASS;
class_path = CLASS_KEY_PATH_9X;
default_class_keys = default_class_keys_9x;
}
i = 0;
while(default_class_keys[i])
{
if((strlen(class_path) + strlen(default_class_keys[i])) < sizeof(tmp))
{
sprintf(tmp, "%s%s", class_path, default_class_keys[i]);
usb_registry_add_class_key(&keys, tmp);
}
i++;
}
dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
dev_info = SetupDiGetClassDevs(NULL, "USB", NULL,
DIGCF_ALLCLASSES);
if(dev_info == INVALID_HANDLE_VALUE)
{
usb_error("usb_registry_get_class_keys(): getting "
"device info set failed");
return NULL;
}
while(SetupDiEnumDeviceInfo(dev_info, dev_index, &dev_info_data))
{
if(!usb_registry_is_service_libusb(dev_info, &dev_info_data))
{
if(!usb_registry_get_property(SPDRP_CLASSGUID, dev_info,
&dev_info_data,
class, sizeof(class)))
{
usb_error("usb_registry_get_class_keys(): getting "
"hardware id failed");
dev_index++;
continue;
}
strlwr(class);
if((strlen(class_path) + strlen(class)) < sizeof(tmp))
{
sprintf(tmp, "%s%s", class_path, class);
usb_registry_add_class_key(&keys, tmp);
}
}
dev_index++;
}
SetupDiDestroyDeviceInfoList(dev_info);
return keys;
}
static usb_class_key_t *usb_registry_get_all_class_keys(void)
{
const char *class_path;
usb_class_key_t *keys = NULL;
HKEY reg_key;
char class[MAX_PATH];
char tmp[MAX_PATH];
if(usb_registry_is_nt())
{
class_path = CLASS_KEY_PATH_NT;
}
else
{
class_path = CLASS_KEY_PATH_9X;
}
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, class_path, 0, KEY_ALL_ACCESS,
®_key) == ERROR_SUCCESS)
{
DWORD i = 0;
DWORD size = sizeof(class);
FILETIME junk;
memset(class, 0, sizeof(class));
while(RegEnumKeyEx(reg_key, i, class, &size, 0, NULL, NULL, &junk)
== ERROR_SUCCESS)
{
strlwr(class);
if((strlen(class_path) + strlen(class)) < sizeof(tmp))
{
sprintf(tmp, "%s%s", class_path, class);
usb_registry_add_class_key(&keys, tmp);
}
memset(class, 0, sizeof(class));
size = sizeof(class);
i++;
}
RegCloseKey(reg_key);
}
return keys;
}
static bool_t usb_registry_add_class_key(usb_class_key_t **head,
const char *key)
{
usb_class_key_t *p = *head;
if(key)
{
if(strlen(key) >= MAX_PATH)
return FALSE;
while(p)
{
if(!strcmp(p->name, key))
{
return FALSE;
}
p = p->next;
}
p = malloc(sizeof(usb_class_key_t));
if(!p)
return FALSE;
memset(p, 0, sizeof(usb_class_key_t));
strcpy(p->name, key);
p->next = *head;
*head = p;
return TRUE;
}
return FALSE;
}
static bool_t usb_registry_free_class_keys(usb_class_key_t **head)
{
usb_class_key_t *p = *head;
usb_class_key_t *q;
while(p)
{
q = p->next;
free(p);
p = q;
}
*head = NULL;
return TRUE;
}
|
tinyos-io/tinyos-3.x-contrib | nxtmote/tos/chips/sensor/c_input.h | #ifndef C_INPUT_H
#define C_INPUT_H
//// c_input.h ////
#define ACTUAL_AD_RES 1023L
#define SENSOR_RESOLUTION 1023L
#define DEBOUNCERELOAD 100
#define THRESHOLD_FALSE (UWORD)(ACTUAL_AD_RES * 45L / 100L)
#define THRESHOLD_TRUE (UWORD)(ACTUAL_AD_RES * 55L / 100L)
#define ANGLELIMITA (UWORD)(ACTUAL_AD_RES * 4400L / 10000L)
#define ANGLELIMITB (UWORD)(ACTUAL_AD_RES * 6600L / 10000L)
#define ANGLELIMITC (UWORD)(ACTUAL_AD_RES * 8900L / 10000L)
#define FWDDIR 1
#define RWDDIR 2
#define MAXSAMPLECNT 5
typedef struct
{
UWORD InvalidTimer[NO_OF_INPUTS];
UBYTE InputDebounce[NO_OF_INPUTS];
UBYTE EdgeCnt[NO_OF_INPUTS];
UBYTE LastAngle[NO_OF_INPUTS];
UBYTE OldSensorType[NO_OF_INPUTS];
UBYTE SampleCnt[NO_OF_INPUTS];
}VARSINPUT;
#endif
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/lib/onewire/usleep.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
*/
/***********************************************************************
* usleep.h -- microsecond-preicision sleep
*/
#ifndef __usleep_h__
#define __usleep_h__
#ifndef CLOCK_MHZ
#error "Please define CLOCK_MHZ to be the system clock speed for usleep()"
#endif
#ifdef USLEEP_CLOCKS_PER_ITER
#undef USLEEP_CLOCKS_PER_ITER
#endif
#ifdef __MSP430__
// mspgcc-recommended delay loop
// -- 3 clocks per iteration
static void __inline__ _usleep(register uint16_t n) {
__asm__ __volatile__ (
"1: \n"
" dec %[n] \n"
" jne 1b \n"
: [n] "+r"(n));
}
#define USLEEP_CLOCKS_PER_ITER 3
#endif
#ifdef __AVR__
// tweaked version of _delay_loop_2 in avr/delay.h
// 4 clocks per iter
static void __inline__ _usleep(register uint16_t n) {
__asm__ __volatile__(
"1: \n"
" sbiw %0, 1 \n" // 2
" brne 1b\n" // 2/1
" nop \n" // 1
: "=w" (n)
: "0" (n));
}
#define USLEEP_CLOCKS_PER_ITER 4
#endif
#ifndef USLEEP_CLOCKS_PER_ITER
#error "Please define the appropriate _usleep() routine for your platform"
#endif
#ifdef _USLEEP_FAC
#undef _USLEEP_FAC
#endif
#define _USLEEP_FAC (((double) CLOCK_MHZ) / ((double) USLEEP_CLOCKS_PER_ITER))
#define usleep(us) _usleep( (((double) (us)) * _USLEEP_FAC) )
#endif
/*** EOF usleep.h */
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/simulator/loadpredictor.h | <filename>eon/eon/src/simulator/loadpredictor.h
#ifndef LOADPREDICTOR_H
#define LOADPREDICTOR_H
#include "simulator.h"
#include "nodes.h"
using namespace std;
#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));
}
int64_t lp_getMaxValue(int64_t limit, bool dolimit)
{
int64_t max = 0;
int i;
for (i=0; i < LOAD_HISTORY; i++)
{
if (history[i] > max && (history[i] < limit || !dolimit))
{
max = history[i];
}
}
return max;
}
void PredictTask()
{
int i= 0;
int samples = LOAD_HISTORY / LOAD_DOUBT;
bool limit = FALSE;
int64_t last_sample, next_sample;
for (i=0; i < samples; i++)
{
last_sample = lp_getMaxValue(last_sample, limit);
limit = TRUE;
}
prediction = last_sample;
}
void hour_past()
{
history[history_index] = event_count;
event_count = 0;
history_index = (history_index +1) % LOAD_HISTORY;
PredictTask();
start_epoch = start_epoch + (EPOCH_HRS * 60 * 60 * 1000);
}
void lp_path_done(int pathNum, int64_t timestamp)
{
int64_t diff = timestamp - start_epoch;
if (diff > (EPOCH_HRS * 60 * 60 * 1000))
{
hour_past();
}
//check that path is not timed.
if (isPathTimed[pathNum]) return;
//else
event_count++;
return;
}
int64_t lp_predict_load(
vector<event_t*>* timeline,
int current_index,
int64_t hours)
{
//give the current prediction in terms of hours.
int64_t result;
result = prediction * hours;
return result;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/lib/industrialCtpRoot/linkestimators/4bitle/LinkEstimator.h | <reponame>tinyos-io/tinyos-3.x-contrib
/*
* "Copyright (c) 2006 University of Southern 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 SOUTHERN 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 SOUTHERN CALIFORNIA HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF SOUTHERN 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
* SOUTHERN CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE,
* SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
*/
/*
* @author <NAME>
*/
#ifndef LINK_ESITIMATOR_H
#define LINK_ESITIMATOR_H
/** Masks for the flag field in the link estimation header */
enum {
// use last four bits to keep track of
// how many footer entries there are
NUM_ENTRIES_FLAG = 15,
};
/*
* The first byte of each outgoing packet is a control byte
* Bits 4..7 reserved for routing and other protocols
* Bits 0..3 is used by the link estimator to encode the
* number of linkest entries in the packet
*
* link estimator header added to
* every message passing through the link estimator
*/
typedef nx_struct linkest_header_t {
nx_uint8_t flags;
nx_uint8_t seq;
} linkest_header_t;
/*
* For outgoing link estimator message so that we can compute bi-directional
* quality
*/
typedef nx_struct neighbor_stat_entry_t {
nx_am_addr_t linkLayerAddress;
nx_uint8_t quality;
} neighbor_stat_entry_t;
/*
* We put the above neighbor entry in the footer
*/
typedef nx_struct linkest_footer_t {
neighbor_stat_entry_t neighborList[1];
} linkest_footer_t;
/*
* Flags for the neighbor table entry
*/
enum {
VALID_ENTRY = 0x1,
// A link becomes mature after BLQ_PKT_WINDOW
// packets are received and an estimate is computed
MATURE_ENTRY = 0x2,
// Flag to indicate that this link has received the
// first sequence number
INIT_ENTRY = 0x4,
// The upper layer has requested that this link be pinned
// Useful if we don't want to lose the root from the table
PINNED_ENTRY = 0x8
};
/*
* Neighbor table entry
*/
typedef struct neighbor_table_entry_t {
// link layer address of the neighbor
am_addr_t linkLayerAddress;
// last beacon sequence number received from this neighbor
uint8_t lastSequence;
// number of beacons received after last beacon estimator update
// the update happens every BLQ_PKT_WINDOW beacon packets
uint8_t receiveCount;
// number of beacon packets missed after last beacon estimator update
uint8_t failCount;
// flags to describe the state of this entry
uint8_t flags;
// MAXAGE-age gives the number of update rounds we haven't been able
// update the inbound beacon estimator
uint8_t age;
// inbound qualities in the range [1..255]
// 1 bad, 255 good
uint8_t quality;
// EETX for the link to this neighbor. This is the quality returned to
// the users of the link estimator
uint16_t eetx;
// Number of data packets successfully sent (ack'd) to this neighbor
// since the last data estimator update round. This update happens
// every DLQ_PKT_WINDOW data packets
uint8_t dataSuccess;
// The total number of data packets transmission attempt to this neighbor
// since the last data estimator update round.
uint8_t dataTotal;
} neighbor_table_entry_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/stargate/rt_intercomm.h | <gh_stars>1-10
#ifndef _RT_INTERCOMM_H_
#define _RT_INTERCOMM_H_
#include "rt_marshall.h"
int intercomm_start(short port);
int intercomm_stop();
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/apps/AIIT_tutorials/4_Single/PrintReading.h | <reponame>tinyos-io/tinyos-3.x-contrib<gh_stars>1-10
#ifndef PRINT_SERIAL_H
#define PRINT_SERIAL_H
#include "message.h"
typedef nx_struct print_reading_msg {
nx_uint8_t flag;
nx_uint8_t buffer[TOSH_DATA_LENGTH - 5];
nx_uint16_t voltage_reading;
nx_uint16_t temperature_reading;
} print_reading_msg_t;
enum {
AM_PRINT_READING_MSG = 0x0B,
FLAG_BUFFER = 0x01,
FLAG_VOLTAGE_READING = 0x02,
FLAG_TEMPERATURE_READING = 0X04,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | tinymulle/tos/chips/m16c62p/m16c62phardware.h | <filename>tinymulle/tos/chips/m16c62p/m16c62phardware.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>>
*/
/**
* Some M16c/62p needed macros and defines.
*
* @author <NAME>
* @author <NAME> <<EMAIL>>
*/
#ifndef __M16C62PHARDWARE_H__
#define __M16C62PHARDWARE_H__
#include "interrupts.h"
#include "iom16c62p.h"
#include "bits.h"
#define true 1
#define false 0
// We need slightly different defs than M16C_INTERRUPT
// for interrupt handlers.
#define M16C_INTERRUPT_HANDLER(id) \
M16C_INTERRUPT(id) @atomic_hwevent() @C()
//Bit operators using bit number
#define _BV(bit) (1 << bit)
#define SET_BIT(port, bit) ((port) |= _BV(bit))
#define CLR_BIT(port, bit) ((port) &= ~_BV(bit))
#define READ_BIT(port, bit) (((port) & _BV(bit)) != 0)
#define FLIP_BIT(port, bit) ((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) ((port) |= (flag))
#define CLR_FLAG(port, flag) ((port) &= ~(flag))
#define READ_FLAG(port, flag) ((port) & (flag))
typedef uint8_t mcu_power_t @combine("ecombine");
// added at 2009-01-27 <NAME>
mcu_power_t mcombine(mcu_power_t m1, mcu_power_t m2) @safe() {
return (m1 < m2) ? m1: m2;
}
enum {
M16C62P_POWER_IDLE = 0, // no use
M16C62P_POWER_ADC_NR = 1, // no use
M16C62P_POWER_EXT_STANDBY = 2, // no use
M16C62P_POWER_SAVE = 3, // no use
M16C62P_POWER_WAIT = 4,
M16C62P_POWER_STOP = 5,
};
// added at 2009-01-27 <NAME>
inline void __nesc_enable_interrupt(void) @safe() { asm("fset i"); }
inline void __nesc_disable_interrupt(void) @safe() { asm("fclr i"); }
/* added at 2009-02-11 by <NAME>. 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; }
typedef uint16_t __nesc_atomic_t;
/**
* Start atomic section.
*/
inline __nesc_atomic_t __nesc_atomic_start(void) @spontaneous() @safe()
{
__nesc_atomic_t result;
// Disable interrupts
__nesc_disable_interrupt();
// Save the flag register (FLG)
asm volatile ("stc flg, %0": "=r"(result): : "%flg");
asm volatile("" : : : "memory"); // ensure atomic section effect visibility
return result;
}
/**
* End atomic section.
*/
inline void __nesc_atomic_end(__nesc_atomic_t original_FLG) @spontaneous() @safe()
{
// Restore the flag register (FLG)
asm volatile("" : : : "memory"); // ensure atomic section effect visibility
asm volatile ("ldc %0, flg": : "r"(original_FLG): "%flg");
}
// If the platform doesnt have defined any main crystal speed it will
// get a default value of 16MHz
#ifndef MAIN_CRYSTAL_SPEED
#define MAIN_CRYSTAL_SPEED 16 /*MHZ*/
#endif
/**
* Input to M16c62pInit.init().
* The cpu speed is derived from 'MAIN_CRYSTAL_SPEED'/M16c62pMainClkDiv.
*/
typedef enum
{
M16C62P_MAIN_CLK_DIV_0 = 0x0,
M16C62P_MAIN_CLK_DIV_2 = 0x1,
M16C62P_MAIN_CLK_DIV_4 = 0x2,
M16C62P_MAIN_CLK_DIV_8 = 0x4,
M16C62P_MAIN_CLK_DIV_16 = 0x3
} M16c62pMainClkDiv;
#endif // __M16C62PHARDWARE_H__
|
tinyos-io/tinyos-3.x-contrib | eon/tos/platforms/turtlenet/sim/hardware.h |
#ifndef _H_hardware_h
#define _H_hardware_h
/*#include "msp430hardware.h"
// XE1205 radio
TOSH_ASSIGN_PIN(NSS_DATA, 1, 0);
TOSH_ASSIGN_PIN(DATA, 5, 7);
TOSH_ASSIGN_PIN(NSS_CONFIG, 1, 4);
TOSH_ASSIGN_PIN(IRQ0, 2, 0);
TOSH_ASSIGN_PIN(IRQ1, 2, 1);
TOSH_ASSIGN_PIN(SW_RX, 2, 6);
TOSH_ASSIGN_PIN(SW_TX, 2, 7);
TOSH_ASSIGN_PIN(POR, 3, 0);
TOSH_ASSIGN_PIN(SCK, 3, 3);
TOSH_ASSIGN_PIN(SW0, 3, 4);
TOSH_ASSIGN_PIN(SW1, 3, 5);
// LED
TOSH_ASSIGN_PIN(RED_LED, 1, 5); // on tinynode
TOSH_ASSIGN_PIN(RED_LED2, 1, 6); // external, for compatibility with Mica
TOSH_ASSIGN_PIN(GREEN_LED, 2, 3);
TOSH_ASSIGN_PIN(YELLOW_LED, 2, 4);
// TOSH_ASSIGN_PIN(RED_LED2, 1, 5); // external, for compatibility with Mica
// TOSH_ASSIGN_PIN(GREEN_LED, 1, 3);
// TOSH_ASSIGN_PIN(YELLOW_LED, 1, 2);
// Other IO
TOSH_ASSIGN_PIN(TEMPE, 5, 4); // optional temperature sensor
TOSH_ASSIGN_PIN(NVSUPE, 5, 5); // voltage supply monitor
TOSH_ASSIGN_PIN(NREGE, 5, 6); // voltage regulator enable
// UART0 pins (shared with XE1205 radio)
TOSH_ASSIGN_PIN(STE0, 3, 0);
TOSH_ASSIGN_PIN(SIMO0, 3, 1);
TOSH_ASSIGN_PIN(SOMI0, 3, 2);
TOSH_ASSIGN_PIN(UCLK0, 3, 3);
TOSH_ASSIGN_PIN(UTXD0, 3, 4);
TOSH_ASSIGN_PIN(URXD0, 3, 5);
// UART1 pins
TOSH_ASSIGN_PIN(STE1, 5, 0);
TOSH_ASSIGN_PIN(SIMO1, 5, 1);
TOSH_ASSIGN_PIN(SOMI1, 5, 2);
TOSH_ASSIGN_PIN(UCLK1, 5, 3);
TOSH_ASSIGN_PIN(UTXD1, 3, 6);
TOSH_ASSIGN_PIN(URXD1, 3, 7);
// ADC
TOSH_ASSIGN_PIN(TEMP, 6, 0); // channel 0: optional temperature sensor
TOSH_ASSIGN_PIN(VSUP, 6, 1); // channel 1: supply monitor
TOSH_ASSIGN_PIN(ADC2, 6, 2);
TOSH_ASSIGN_PIN(ADC3, 6, 3);
TOSH_ASSIGN_PIN(ADC4, 6, 4);
TOSH_ASSIGN_PIN(ADC5, 6, 5);
TOSH_ASSIGN_PIN(ADC6, 6, 6);
TOSH_ASSIGN_PIN(ADC7, 6, 7);
// External FLASH
TOSH_ASSIGN_PIN(NFL_RST, 4, 6);
TOSH_ASSIGN_PIN(NFL_CS, 4, 7);
TOSH_ASSIGN_PIN(FLASH_RST, 4, 6);
TOSH_ASSIGN_PIN(FLASH_CS, 4, 7);
// PROGRAMMING PINS (tri-state)
TOSH_ASSIGN_PIN(PROG_RX, 1, 1);
TOSH_ASSIGN_PIN(PROG_TX, 2, 2);
// Oscillator resistance
TOSH_ASSIGN_PIN(ROSC, 2, 5);
// unused
TOSH_ASSIGN_PIN(P12, 1, 2);
TOSH_ASSIGN_PIN(P13, 1, 3);
TOSH_ASSIGN_PIN(P16, 1, 6);
TOSH_ASSIGN_PIN(P23, 2, 3);
TOSH_ASSIGN_PIN(P24, 2, 4);
TOSH_ASSIGN_PIN(P40, 4, 0);
TOSH_ASSIGN_PIN(P41, 4, 1);
// unconnected
TOSH_ASSIGN_PIN(NOT_CONNECTED1, 1, 7);
TOSH_ASSIGN_PIN(NOT_CONNECTED2, 4, 2);
TOSH_ASSIGN_PIN(NOT_CONNECTED3, 4, 3);
TOSH_ASSIGN_PIN(NOT_CONNECTED4, 4, 4);
TOSH_ASSIGN_PIN(NOT_CONNECTED5, 4, 5);
void TOSH_SET_PIN_DIRECTIONS(void)
{
//LEDS
TOSH_CLR_RED_LED_PIN();
TOSH_MAKE_RED_LED_OUTPUT();
// XE1205 radio
// TOSH_SET_NSS_DATA_PIN();
// TOSH_MAKE_NSS_DATA_OUTPUT();
// TOSH_CLR_DATA_PIN();
// TOSH_MAKE_DATA_OUTPUT();
// TOSH_SET_NSS_CONFIG_PIN();
// TOSH_MAKE_NSS_CONFIG_OUTPUT();
// TOSH_CLR_IRQ0_PIN();
// TOSH_MAKE_IRQ0_OUTPUT();
// TOSH_CLR_IRQ1_PIN();
// TOSH_MAKE_IRQ1_OUTPUT();
// TOSH_CLR_SW_RX_PIN();
// TOSH_MAKE_SW_RX_OUTPUT();
// TOSH_CLR_SW_TX_PIN();
// TOSH_MAKE_SW_TX_OUTPUT();
TOSH_MAKE_POR_INPUT();
// SPI0
TOSH_CLR_SCK_PIN();
TOSH_MAKE_SCK_OUTPUT();
// antenna switch
// TOSH_CLR_SW0_PIN();
// TOSH_MAKE_SW0_OUTPUT();
// TOSH_CLR_SW1_PIN();
// TOSH_MAKE_SW1_OUTPUT();
// optional temperature sensor
TOSH_CLR_TEMPE_PIN();
TOSH_MAKE_TEMPE_OUTPUT();
TOSH_MAKE_TEMP_INPUT();
TOSH_SEL_TEMP_MODFUNC();
// voltage supply monitor
TOSH_SET_NVSUPE_PIN();
TOSH_MAKE_NVSUPE_INPUT();
TOSH_MAKE_VSUP_INPUT();
TOSH_SEL_VSUP_MODFUNC();
// voltage regulator
TOSH_SET_NREGE_PIN(); // disable regulator for low power mode
TOSH_MAKE_NREGE_OUTPUT();
//UART PINS
TOSH_MAKE_UTXD1_INPUT();
TOSH_MAKE_URXD1_INPUT();
TOSH_SEL_UTXD1_IOFUNC();
// External FLASH
TOSH_SET_FLASH_RST_PIN();
TOSH_MAKE_FLASH_RST_OUTPUT();
TOSH_SET_FLASH_CS_PIN();
TOSH_MAKE_FLASH_CS_OUTPUT();
//PROG PINS
TOSH_MAKE_PROG_RX_INPUT();
TOSH_MAKE_PROG_TX_INPUT();
// ROSC PIN
TOSH_SET_ROSC_PIN();
TOSH_MAKE_ROSC_OUTPUT();
// set unconnected pins to avoid instability
TOSH_SET_NOT_CONNECTED1_PIN();
TOSH_SET_NOT_CONNECTED2_PIN();
TOSH_SET_NOT_CONNECTED3_PIN();
TOSH_SET_NOT_CONNECTED4_PIN();
TOSH_SET_NOT_CONNECTED5_PIN();
TOSH_MAKE_NOT_CONNECTED1_OUTPUT();
TOSH_MAKE_NOT_CONNECTED2_OUTPUT();
TOSH_MAKE_NOT_CONNECTED3_OUTPUT();
TOSH_MAKE_NOT_CONNECTED4_OUTPUT();
TOSH_MAKE_NOT_CONNECTED5_OUTPUT();
}
*/
typedef uint8_t __nesc_atomic_t;
__nesc_atomic_t __nesc_atomic_start(void);
void __nesc_atomic_end(__nesc_atomic_t original_SREG);
inline void __nesc_enable_interrupt() { }
inline void __nesc_disable_interrupt() { }
inline __nesc_atomic_t __nesc_atomic_start(void) {
return 0;
}
/* Restores interrupt mask to original state. */
inline void __nesc_atomic_end(__nesc_atomic_t original_SREG) {
}
#endif // _H_hardware_h
|
tinyos-io/tinyos-3.x-contrib | antlab-polimi/dpcm_C/dpcm_decoder.h | #include <stdio.h>
#include "diff_idctfstBlk.h"
#include "diff_dctfstBlk.h"
#include "decodeZeros.h"
#include "huffmanUncompress.h"
#include "jpeghdr.h"
#include "quanttables.h"
int getBytes(char* filename, uint8_t *dataIn)
{
FILE *fdIn;
if (!(fdIn = fopen(filename, "r")) ){
printf("Can't open %s for reading\n", filename);
return -1;
}
int8_t line[1024];
int count, dataSize=0;
while( (count=fread(line, 1, 1024, fdIn))>0)
{
memcpy(&(dataIn[dataSize]),line,count);
dataSize+=count;
}
fclose(fdIn);
return dataSize;
}
int read_dimensions_from_compressed_file(code_header_t* header, char* filename) {
unsigned char dataBuffer[1024];
FILE *fdIn;
if (!(fdIn = fopen(filename, "r")) ){
printf("Can't open %s for reading its header\n", filename);
return -11;
}
uint8_t line[1024];
int count;
count=fread(line, 1, 1024, fdIn);
memcpy(dataBuffer,line,count);
fclose(fdIn);
memcpy(header,dataBuffer,CODE_HEADER_SIZE);
return count;
}
int dpcm_decode(char * filename,uint8_t frame_num, char* output_name){
FILE* fdB;
FILE* fdImg;
char* file_buffer="buffer_receiver";
char* save_path="src/pictures/";
code_header_t header[CODE_HEADER_SIZE];
char out_img[1024];
int i,j;
//creating name of the output image
out_img[0]='\0';
strcat(out_img,save_path);
for(i=0; i<=strlen(filename); i++) {
out_img[strlen(save_path)+i]=output_name[i];
}
sprintf(&out_img[i++],"%d",frame_num);
out_img[i]='\0';
strcat(out_img,"_rec.pgm");
// color settings
int bufShift=1; // B&W
// read the received image
read_dimensions_from_compressed_file(header, filename);
// build structures
printf("Width: %d; Height: %d\n",header->width,header->height);
uint8_t buffer[header->width*header->height];
uint8_t received_img[header->width*header->height];
int8_t recovered_diff[header->width*header->height];
uint8_t recovered_img[header->width*header->height];
// read the buffer
if ( frame_num>0 && (fdB = fopen(file_buffer, "r"))!=NULL )
{
uint8_t line[1024];
int count, dataSize=0;
while( (count=fread(line, 1, 1024, fdB))>0) {
memcpy(&(buffer[dataSize]),line,count);
dataSize+=count;
}
fclose(fdB);
}
else if( frame_num > 0 ) {
printf("Error reading buffer\n");
return -1;
}
// read image received
getBytes(filename,received_img);
// decode received image
printf("DECODE hdr (%dx%d, qual=%d, col=%d, sizeRLE=%d, sizeHUF=%d, totSize=%d)\n",
header->width,header->height,header->quality,
header->is_color,header->sizeRLE,header->sizeHUF,header->totalSize);
unsigned char *dataIn=&received_img[CODE_HEADER_SIZE];
unsigned char dataTmp[header->sizeRLE];
uint32_t max_size = header->width*header->height;
uint32_t dc_size = max_size/64;
int8_t dct_decoded[header->width*header->height];
Huffman_Uncompress(dataIn, dataTmp, header->sizeHUF, header->sizeRLE);
decodeDC(dataTmp,(uint8_t *) dct_decoded, dc_size);
decodeZeros(&dataTmp[dc_size],(uint8_t *) &dct_decoded[dc_size], header->sizeRLE, max_size-dc_size);
//find num of blocks
uint16_t width=header->width;
uint16_t height=header->height;
uint8_t w_blocks=width>>3;
uint8_t h_blocks=height>>3;
uint16_t total_blocks= w_blocks*h_blocks;
for (i=0; i<w_blocks; i++)
for (j=0; j<h_blocks; j++)
{
diff_idctNew(i,j,total_blocks,
dct_decoded,recovered_diff,bufShift,
QUANT_TABLE,header->quality,width);
}
//sum the buffer
if(frame_num==0){
for(i=0;i<width*height;i++){
buffer[i]=recovered_diff[i]+128;
recovered_img[i]=buffer[i];
}
}
else{
for(i=0;i<width*height;i++){
if(buffer[i]+recovered_diff[i]*2<0){
buffer[i]=0;
}
else if(buffer[i]+recovered_diff[i]*2>255) {
buffer[i]=255;
}
else buffer[i]=buffer[i]+recovered_diff[i]*2;
recovered_img[i]=buffer[i];
}
}
//printf("Pre image\n");
FILE *fdBD;
if ((fdBD = fopen("buffer_debug", "w")))
{
for(i=0;i<width*height;i++)
fprintf(fdBD,"%d\n",buffer[i]);
fclose(fdBD);
}
else {
printf("Error writing buffer.\n");
return -1;
}
// write new buffer
if ((fdB = fopen(file_buffer, "w"))) {
fwrite(buffer,1,width*height,fdB);
fclose(fdB);
}
else {
printf("Error updating buffer.\n");
return -1;
}
// write reconstructed image on file
printf("Writing file %s\n",out_img);
if ((fdImg = fopen(out_img, "w")))
{
// fprintf(fdImg, "P5\n\n%d %d\n255\n", width, height);
fwrite(recovered_img,1,width*height,fdImg);
fclose(fdImg);
printf("Image correctly reconstructed.\n");
}
else {
printf ("Error opening out_img");
}
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/linuxsim/evaluator.c | #include <pthread.h>
#include "energymgr.h"
//#include <stdint.h>
#include "../mNodes.h"
#include <math.h>
#ifndef NUMTIMEFRAMES
#define NUMTIMEFRAMES 12
#endif
#ifdef STATIC_POLICY
int static_state = STATIC_STATE;
double static_grade = STATIC_GRADE;
#endif
int ENERGY_TIMESCALES[NUMTIMEFRAMES];
extern unsigned int __path_costs[NUMPATHS];
extern unsigned int __path_count[NUMPATHS];
extern unsigned int __path_pred_count[NUMPATHS][NUMSTATES];
extern int idle_uW;
void init_evaluator()
{
int i;
// printf("NUMTIMEFRAMES = %d\n",NUMTIMEFRAMES);
ENERGY_TIMESCALES[0] = 1;
for (i=1; i < NUMTIMEFRAMES; i++)
{
ENERGY_TIMESCALES[i] = ENERGY_TIMESCALES[i-1]*2;
}
printf("init_evaluator done\n");
}
int64_t predict_consumption(int64_t hours, int state, double grade)
{
uint64_t energysum = 0;
uint64_t pathsum = 0;
uint64_t timedrate;
uint64_t maxrate, minrate;
int i=0;
int j=0;
for (i=0; i < NUMPATHS; i++)
{
if (!isPathTimed[i])
{
//cost of path
pathsum = __path_pred_count[i][state];
pathsum = pathsum * __path_costs[i];
pathsum = pathsum * hours;
energysum += pathsum;
}
}
//now add timed srcs
for (j=0; j < NUMSOURCES; j++)
{
for (i=0; i < NUMPATHS; i++)
{
if (pathSrc[i] == j)
{
if (isPathTimed[i])
{
double tdelta = (double)(timerVals[j][state][1]-timerVals[j][state][0]);
double dval = ((double)timerVals[j][state][1]) - (grade * tdelta);
uint32_t newval = (uint32_t)rint(dval);
timedrate = (3600000 * hours) / newval;
pathsum = (timedrate) * (__path_costs[i]);
energysum += pathsum;
//printf("cp-->td=%lf,dv=%lf,nv=%ld,rate=%lld,p=%d,e=%lld --> es=%lld\n",
// tdelta,dval,newval,timedrate,cp_prob[i],cp_pathenergy[i],energysum);
} else {
break;
}
}
}
}
//printf("predict_consumption(%lld, %lld, %d, %lf)->%lld\n",hours,xevents,state,grade,energysum);
energysum += (idle_uW * hours * 3600);
return energysum;
}
int64_t predict_energy (uint8_t timeframe, uint8_t state, double grade)
{
int64_t src_energy;
int64_t consumption;
int64_t load;
int64_t netenergy, idleloss;
if (state > NUMSTATES)
{
printf("ERROR: Invalid state!!! (s=%d)\n",state);
exit(2);
}
src_energy = predict_src_energy(ENERGY_TIMESCALES[timeframe]);//predict source
consumption = predict_consumption(ENERGY_TIMESCALES[timeframe], state, grade);
netenergy = src_energy - consumption;
//printf("predict_energy(%lld, %d, %d, %lf)->(%lld,%lld,%lld,%lld)\n",
// current_index,timeframe,state,grade,src_energy,load,consumption, idleloss);
return netenergy;
}
bool predict_state (int64_t thebattery, int64_t battery_capacity,
uint8_t state, double grade, int64_t *energy_result)
{
int timeframe = 0;
uint64_t waste_energy = 0;
int64_t netenergy, newbattery = 0;
int64_t immediate_waste = 0;
bool dead = FALSE;
int64_t battery;
battery = thebattery;
while (timeframe < NUMTIMEFRAMES && !dead)
{
dead = TRUE;
netenergy = predict_energy(timeframe, state, grade);
newbattery = battery + netenergy - waste_energy;
if (energy_result != NULL)
{
*energy_result = newbattery;
}
if (newbattery <= battery_capacity)
{
immediate_waste = 0;
} else {
immediate_waste = newbattery - battery_capacity;
newbattery = battery_capacity;
}
waste_energy += immediate_waste;
//printf("t=%d---s=%d --> ",timeframe, state);
//printf("(%lld,%lld,%lld,%lld)\n",battery, netenergy, waste_energy, immediate_waste);
if (newbattery <= 0)
{
dead = TRUE;
//printf("DEAD!\n");
} else {
dead = FALSE;
//printf("Not Dead\n");
}
if (!dead)
{
timeframe++;
}
}
return !dead;
}
energy_evaluation_struct_t *reevaluate_energy_level(int64_t battery_state, int64_t battery_capacity)
{
energy_evaluation_struct_t * ret = (energy_evaluation_struct_t*)malloc(sizeof(energy_evaluation_struct_t));
uint8_t state = 0; //set to max state
bool minalive = FALSE;
bool maxalive;
int64_t minenergy = 0;
int64_t maxenergy = 0;
while (state <= STATE_BASE && !minalive)
{
minalive = predict_state(battery_state, battery_capacity, state, 0.0, &minenergy);
if (!minalive)
{
state++;
}
}
//we have the right state...now get the grade
if (!minalive)
{
state = STATE_BASE;
ret->state_grade = 0.0;
} else {
maxalive = predict_state(battery_state, battery_capacity, state, 1.0, &maxenergy);
if (maxalive)
{
ret->state_grade = 1.0;
} else {
double mingrade = 0.0;
double maxgrade = 1.0;
double midgrade;
while ((maxgrade - mingrade) > .001)
{
midgrade = (mingrade + maxgrade)/2;
if (predict_state(battery_state, battery_capacity, state, midgrade,NULL))
{
mingrade = midgrade;
} else {
maxgrade = midgrade;
}
}
ret->state_grade = midgrade;
}
}
ret->energy_state = state;
ret->cost_of_reevaluation = 0;
printf("state = %d(%lf)\n",state, ret->state_grade);
return ret;
}
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/chips/msp430/dac12/vref/msp430vref.h |
#ifndef MSP430VREF_H
#define MSP430VREF_H
/** Time for generator to become stable (don't change). */
#define STABILIZE_INTERVAL 17
/**
* Delay before generator is switched off after it has been stopped (in ms).
* This avoids having to wait the 17ms in case the generator is needed again
* shortly after it has been stopped (value may be modified).
*/
#define SWITCHOFF_INTERVAL 20
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libnxt/samba.c | /**
* 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
*/
#include <stdio.h>
#include <string.h>
#include "error.h"
#include "lowlevel.h"
#include "samba.h"
static nxt_error_t
nxt_format_command2(char *buf, char cmd,
nxt_addr_t addr, nxt_word_t word)
{
snprintf(buf, 20, "%c%08X,%08X#", cmd, addr, word);
return NXT_OK;
}
static nxt_error_t
nxt_format_command(char *buf, char cmd, nxt_addr_t addr)
{
snprintf(buf, 20, "%c%08X#", cmd, addr);
return NXT_OK;
}
static nxt_error_t
nxt_write_common(nxt_t *nxt, char type, nxt_addr_t addr, nxt_word_t w)
{
char buf[21] = {0};
NXT_ERR(nxt_format_command2(buf, type, addr, w));
NXT_ERR(nxt_send_str(nxt, buf));
return NXT_OK;
}
nxt_error_t
nxt_write_byte(nxt_t *nxt, nxt_addr_t addr, nxt_byte_t b)
{
return nxt_write_common(nxt, 'O', addr, b);
}
nxt_error_t
nxt_write_hword(nxt_t *nxt, nxt_addr_t addr, nxt_hword_t hw)
{
return nxt_write_common(nxt, 'H', addr, hw);
}
nxt_error_t
nxt_write_word(nxt_t *nxt, nxt_addr_t addr, nxt_word_t w)
{
return nxt_write_common(nxt, 'W', addr, w);
}
static nxt_error_t
nxt_read_common(nxt_t *nxt, char cmd, int len,
nxt_addr_t addr, nxt_word_t *word)
{
char buf[20] = {0};
nxt_word_t w;
NXT_ERR(nxt_format_command2(buf, cmd, addr, len));
NXT_ERR(nxt_send_str(nxt, buf));
NXT_ERR(nxt_recv_buf(nxt, buf, len));
w = *((nxt_word_t*)buf);
#ifdef _NXT_BIG_ENDIAN
/* The value returned is in little-endian byte ordering, so swap
bytes on a big-endian architecture. */
w = (((w & 0x000000FF) << 24) +
((w & 0x0000FF00) << 8) +
((w & 0x00FF0000) >> 8) +
((w & 0xFF000000) >> 24));
#endif /* _NXT_BIG_ENDIAN */
*word = w;
return NXT_OK;
}
nxt_error_t
nxt_read_byte(nxt_t *nxt, nxt_addr_t addr, nxt_byte_t *b)
{
nxt_word_t w;
NXT_ERR(nxt_read_common(nxt, 'o', 1, addr, &w));
*b = (nxt_byte_t)w;
return NXT_OK;
}
nxt_error_t
nxt_read_hword(nxt_t *nxt, nxt_addr_t addr, nxt_hword_t *hw)
{
nxt_word_t w;
NXT_ERR(nxt_read_common(nxt, 'h', 2, addr, &w));
*hw = (nxt_hword_t)w;
return NXT_OK;
}
nxt_error_t
nxt_read_word(nxt_t *nxt, nxt_addr_t addr, nxt_word_t *w)
{
return nxt_read_common(nxt, 'w', 4, addr, w);
}
nxt_error_t
nxt_send_file(nxt_t *nxt, nxt_addr_t addr, char *file, unsigned short len)
{
char buf[20];
NXT_ERR(nxt_format_command2(buf, 'S', addr, len));
NXT_ERR(nxt_send_str(nxt, buf));
NXT_ERR(nxt_send_buf(nxt, file, len));
return NXT_OK;
}
nxt_error_t
nxt_recv_file(nxt_t *nxt, nxt_addr_t addr, char *file, unsigned short len)
{
char buf[20];
NXT_ERR(nxt_format_command2(buf, 'R', addr, len));
NXT_ERR(nxt_send_str(nxt, buf));
NXT_ERR(nxt_recv_buf(nxt, file, len+1));
return NXT_OK;
}
nxt_error_t
nxt_jump(nxt_t *nxt, nxt_addr_t addr)
{
char buf[20];
NXT_ERR(nxt_format_command(buf, 'G', addr));
NXT_ERR(nxt_send_str(nxt, buf));
return NXT_OK;
}
nxt_error_t
nxt_samba_version(nxt_t *nxt, char *version)
{
char buf[3];
strcpy(buf, "V#");
NXT_ERR(nxt_send_str(nxt, buf));
NXT_ERR(nxt_recv_buf(nxt, version, 4));
version[4] = 0;
return NXT_OK;
}
|
tinyos-io/tinyos-3.x-contrib | wsu/tools/simx/simx/lib/simx/sync/sync_impl.c | /*
* Bridge to allow TOSSIM applications to run simulation events "in
* real-world" time.
*
* WARNING:: It is assumed that sim_time_t is a small multiple of a
* nano-second (10 by default). Adjust TICKS_PER_NSEC below as needed.
*/
#ifdef __cplusplus
extern "C" {
#endif
#if 0
}
#endif
#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <errno.h>
#include <sim_tossim.h>
#include <sim_event_queue.h>
/* watch out the C -- explicit widen */
#define K (1000LL)
#define NSEC_PER_SEC (K * K * K)
#define MSEC_PER_NSEC (K * K)
#define USEC_PER_NSEC (K)
#define TICKS_PER_NSEC 10
#define TICKS_PER_SEC (NSEC_PER_SEC * TICKS_PER_NSEC)
#define SECS_TO_TICKS(sec) ((sim_time_t)(sec) * TICKS_PER_SEC)
#define MSEC_TO_NSEC(ms) ((sim_time_t)(ms) * MSEC_PER_NSEC)
#define MSEC_TO_TICKS(ms) (MSEC_TO_NSEC(ms) * TICKS_PER_NSEC)
#define USEC_TO_NSEC(us) ((sim_time_t)(us) * USEC_PER_NSEC)
#define USEC_TO_TICKS(us) (USEC_TO_NSEC(us) * TICKS_PER_NSEC)
/*
* Minimum time to sleep in nanosecods. This can avoid a nanosleep
* system call and may be beneficial when many events are pooled very
* close together.
*
* WARNING: Because this 'pools events' it prevents real-world time
* pacing and and prohibits forced advancement. Thus, the value should
* be kept relatively small.
*/
#define MIN_SLEEP_TIME USEC_TO_NSEC(500)
sim_time_t sync_time = 0; /* real-world time of last sync. */
sim_time_t sync_simtime = 0; /* simtime of last sync. */
sim_time_t stop_at = 0; /* if non zero, max time to run until */
long double clock_mul = 1; /* clock multiplier, high res. for mul */
/*
* Return real-world time in "ticks".
*/
sim_time_t sync_get_real_time() {
struct timeval tv;
if(gettimeofday(&tv, NULL) == 0) {
return SECS_TO_TICKS(tv.tv_sec) + USEC_TO_TICKS(tv.tv_usec);
} else {
perror("gettimeofday() failed");
return 0;
}
}
/*
* Synchronize with the current time. This is used to control pacing
* in sync_event_wait. It should be called whenever a simulation
* enters a "running mode" and before the invokation of
* sync_event_wait.
*/
void sync_synchronize() {
sync_time = sync_get_real_time();
sync_simtime = sim_time();
}
/*
* Set the clock multiplier and synchronize the simulation time. If a
* multiplier of 0 (or less) is specified sync_wait_event fast-returns
* (as time can not be advanced).
*/
void sync_set_clock_mul(float new_clock_mul) {
if (new_clock_mul > 0) {
sync_synchronize();
}
clock_mul = new_clock_mul;
}
float sync_get_clock_mul() {
return clock_mul;
}
/*
* Sets the "stop at" time. sync_event_wait can be instructed to honor
* this value and keep the simulation from advancing past a certain
* simulation time.
*
* A value of 0 disables the "stop at" feature.
*/
void sync_set_stop_at(sim_time_t new_stop_at) {
stop_at = new_stop_at;
}
sim_time_t sync_get_stop_at() {
return stop_at;
}
/*
* Waits for the specified amount of nano-seconds, reporting and then
* ignoring interruptions. Returns 0 on success.
*/
int wait_uninterrupted (long long int wait_nsec) {
struct timespec req;
req.tv_sec = wait_nsec / NSEC_PER_SEC;
req.tv_nsec = wait_nsec - (long long int)req.tv_sec * NSEC_PER_SEC;
while (nanosleep(&req, &req) == -1) {
/* nanosleep modifies 2nd arg. */
if (EINTR == errno) {
perror("nanosleep() interrupted");
} else {
perror("nanosleep() failed");
return -1;
}
}
return 0;
}
/*
* Wait from now to target with a max wait of max_wait_nsec. `now' and
* `target' represent REAL WORLD TIME, in ticks. All values must be
* non-negative.
*
* Returns 1 if, after the wait, the target time was reached or is in
* within some delta of the current time. Otherwise 0 is returned.
*/
static int sync_wait_until(sim_time_t now, sim_time_t target,
long max_wait_msec) {
if (target <= now) {
/* target is now or in past */
return 1;
} else {
/* event in future */
sim_time_t wait_nsec = (target - now) / TICKS_PER_NSEC;
if (wait_nsec <= MIN_SLEEP_TIME) {
/* wait period too small */
return 1;
} else if (MSEC_TO_NSEC(max_wait_msec) < wait_nsec) {
/* timeout before event */
wait_uninterrupted(MSEC_TO_NSEC(max_wait_msec));
return 0;
} else {
/* wait full */
wait_uninterrupted(wait_nsec);
return 1;
}
}
}
/*
* Run the next TOSSIM event at the correct pacing according the clock
* multiplier (see sync_set_clock_mul) while not proceeding past the
* stop-at time (see sync_set_stop_at). If the next event is now, or
* in the past, no waiting occurs.
*
* max_wait_msec specifies the maximum real-world time to wait, in
* milliseconds. It should be >= 0.
*
* If force_advance is non-0 then, even if there were no real events
* during the timeout period, the simulation time will be
* advanced. This keeps the simulation time from "falling behind"
* during periods of no-events.
*
* If ignore_stop_at is non-0 then the stop_at time will be
* ignored. Otherwise, is stop_at is not 0, the simulation will be
* prohibited from running past the stop-at time.
*
* Returns 0 if there is no event to process, -1 if at stop time (and
* no events to process), or 1 if there is an event to process now.
*
* If the clock_mul is disabled then 1 will be returned if there is an
* event on the queue, 0 otherwise.
*/
int sync_event_wait(long max_wait_msec,
int force_advance,
int ignore_stop_at) {
int stop_check = !ignore_stop_at && stop_at;
sim_time_t target = sim_queue_peek_time();
if (stop_check && stop_at <= sim_time()) {
/* quick-path when stopped */
return stop_at < 0 || stop_at != target ? -1 : 1;
} else if (clock_mul <= 0) {
/* quick-path for no clock-mul */
return target >= 0;
} else {
sim_time_t since_sync = sync_get_real_time() - sync_time;
sim_time_t wait_to = sync_simtime + (since_sync * clock_mul);
int result;
/* don't wait past stop at time */
/* stop_at > sim_time(), from quick-path above */
if (stop_check && wait_to > stop_at) {
wait_to = stop_at;
}
if (max_wait_msec < 0) {
fprintf(stderr, "sync_event_wait: invalid max_wait_msec\n");
max_wait_msec = 0;
}
result = sync_wait_until(wait_to, target, max_wait_msec);
if (!result && force_advance) {
sim_time_t force_to = sim_time() +
(MSEC_TO_TICKS(max_wait_msec) * clock_mul);
/* don't advance past stop at time */
/* stop_at > sim_time(), from quick-path above */
if (stop_check && force_to > stop_at) {
force_to = stop_at;
}
/* force_to > sim_time() since max_wait_msec >= 0 by above */
sim_set_time(force_to);
/* result = 0 from conditional guard */
}
return result;
}
}
#ifdef __cplusplus
}
#endif
|
tinyos-io/tinyos-3.x-contrib | diku/freescale/tos/chips/hcs08/hcs08hardware.h | <filename>diku/freescale/tos/chips/hcs08/hcs08hardware.h
// $Id: hcs08hardware.h,v 1.3 2008/10/26 20:44:40 mleopold 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."
*/
// @author <NAME> <<EMAIL>>
// @author <NAME> <<EMAIL>>
// @author <NAME> <<EMAIL>>
#ifndef _H_hcs08hardware_h
#define _H_hcs08hardware_h
#include "hcs08gt60_interrupts.h"
//#include "hcs08gb60.h"
#include "hcs08regs.h"
// see hcs08gb60_interrupts.h for a list of available interrupts
// SIGNAL means interrupts are disabled within the handler
#define TOSH_SIGNAL(signame) \
void signal_##signame() __attribute__ ((interrupt, spontaneous, C))
// just don't support TOSH_INTERRUPT, thus eliminating confusion
/** Declare the ANSI startup function, see below (TinyOSStartup) */
extern void _Startup(void) __attribute__((C, spontaneous));
/**
*
* Our TinyOSStartup code.
*
* <p>Now, here there be tigers. In order to disable the watchdog,
* before the ANSI startup code (from CW: Start08.c) is run, we define
* our own startup code. This code simply disables the watchdog
* (configure the SOPT register). Because most of the SOPT register
* bits are write once, we setup the entire register here. And here
* comes the tigers: Because the ANSI startup code have not been run,
* the stack pointer have _not_ been setup. Neither have the data
* variables been copied to ram, nor have the global variables been
* zero initialized. In other words: Do _not_ use the stack, do _not_
* use global variables, or even global consts in this function! (No
* strings, no initialized variables, no statements like char buf[2] =
* 0; anything like that. In fact, check the assembler every time you
* change this function.</p>
*
* <p>Oh, and in order to be able to jump to _Startup, we have to
* declare it as above. The rest is done through the linker
* script.</p>
*
* SOPT Bits:
* bit 7 = watchdog (0 disabled)
* bit 6 = watchdog timeout
* bit 5 = stop mode enable (0 disabled)
* bit 4 = 1
* bit 1 = background debug mode enabled
* bit 0 = 1 */
#define ICG_FILTER_MSB 0x02;
#define ICG_FILTER_LSB 0x40; // LSB value must be written first
#pragma NO_EXIT /* Dunno if this goes all the way through, assembler
looks good though. */
void _TinyOSStartup() __attribute__((C, spontaneous))
{
// Disable watchdog.
SOPT = 0x71;
// Starting up in SCM mode 16 MHz system clock.
ICGFLTL = ICG_FILTER_LSB; // LSB value must be written first
ICGFLTU = ICG_FILTER_MSB;
asm ("jmp _Startup");
}
/**
* Set up a couple of bits of the SPMSC2
*
*/
// #define DEBUG_SLEEP
#ifdef DEBUG_SLEEP
uint32_t schedules;
#endif
#pragma INLINE
void configureLowLevelRegisters() {
#ifdef DEBUG_SLEEP
schedules = 0;
#endif
SPMSC2 = 0x0; // I believe I was fiddling with some sleep modes...
}
/**
* MBD: The MCU supports a number of stop/sleep modes.
* For now, I opt for something very simple, the wait mode. */
extern uint8_t Mlme_Main(void);
void TOSH_sleep()
{
// Allow the 802.15.4 stack to do what it needs to do
#ifdef INCLUDEFREESCALE802154
while(Mlme_Main());
// asm( "WAIT" ); // This should work, not sure if it does or not.
#else
// asm( "STOP" ); // Do not work at the moment.
asm( "WAIT" );
#endif
#ifdef DEBUG_SLEEP
++schedules;
#endif
}
// Serial line debug functions
void initSer()
{
//SCI2BD = 8000000/(16*38400);
//SCI2C2 = 0x8;
}
void putSer(uint8_t data)
{
// Wait for Transmit Data Register to be empty.
while(!SCI2S1_TDRE);
SCI2D = data;
// Wait for Transmission Complete.
while(!SCI2S1_TC);
}
// Functions for writing to flash from user apps.
// Remember to set FCDIV to scale the flash clock into
// the 150 - 200 KHz range. Closer to 200 means faster operation.
// For 16 MHz operation FCDIV = 0x27 is optimal.
typedef void (*flashfunc)(char *data, uint16_t addr, uint8_t len);
flashfunc flashWrite = (flashfunc)(0xFF8B);
uint32_t busClock = 8000000; // We init busClock to be 8 MHz.
uint32_t extClock;
uint32_t fIRG = 250000; // f_IRG is 243 KHz, but 250 KHz gives nice round numbers.
void enterFEIMode(uint8_t multFact, uint8_t divFact)
{
// f_IRG = 243 KHz
// f_ICGOUT = (f_IRG / 7) * 64 * multFact / divFact
// 16 MHz = ( 243 kHz / 7) * 64 * 14 / 2
// multFact : 4, 6, 8, 10, 12, 14, 16, 18
// divFact : 1, 2, 4, 8, 16, 32, 64, 128
uint8_t MFD, RFD = 0;
// Set busClock variable.
busClock = (fIRG / 7) * 64 * (multFact / divFact)/2;
// Calculate MFD bits.
MFD = (multFact - 4)>>1;
MFD &= 0x07;
// Calculate RFD bits.
while (divFact) {
divFact = divFact>>1;
RFD++;
}
RFD--;
RFD &= 0x07;
// Set clock into FEI mode.
ICGC1 = 0x28; //00101000, REFS = 1, CLKS = 1.
while (!ICGS2_DCOS); // Wait for DCO to be stable.
ICGC2_MFD = MFD;
ICGC2_RFD = RFD;
ICGC2_LOLRE = 0;
ICGC2_LOCRE = 0;
}
void enterFBEMode(uint8_t divFact)
{
// f_ICGOUT = f_EXT / divFact
// divFact : 1, 2, 4, 8, 16, 32, 64, 128
uint8_t RFD = 0;
// Set busClock variable.
busClock = (extClock / divFact)/2;
// Calculate RFD bits.
while (divFact) {
divFact = divFact>>1;
RFD++;
}
RFD--;
RFD &= 0x07;
// Set clock into FBE mode.
ICGC1 = 0x50; // 01010000, RANGE = 1, CLKS = 2.
while (!ICGS1_ERCS); // Wait for External Clock to be stable.
ICGC2_RFD = RFD;
ICGC2_LOLRE = 0;
ICGC2_LOCRE = 0;
}
void enterFEEMode(bool rng, uint8_t multFact, uint8_t divFact)
{
// f_ICGOUT = f_EXT * (64*!rng) * multFact / divFact
// multFact : 4, 6, 8, 10, 12, 14, 16, 18
// divFact : 1, 2, 4, 8, 16, 32, 64, 128
uint8_t MFD, RFD = 0;
// Set busClock variable.
busClock = (extClock * (64*!rng) * (multFact / divFact))/2;
// Calculate MFD bits.
MFD = (multFact - 4)>>1;
MFD &= 0x07;
// Calculate RFD bits.
while (divFact) {
divFact = divFact>>1;
RFD++;
}
RFD--;
RFD &= 0x07;
// Set clock into FEE mode.
if (rng) {
ICGC1 = 0x58; // 01011000
} else {
ICGC1 = 0x18; // 00011000
}
while (!ICGS2_DCOS || !ICGS1_ERCS); // Wait for DCO and External Clock to be stable.
ICGC2_MFD = MFD;
ICGC2_RFD = RFD;
ICGC2_LOLRE = 0;
ICGC2_LOCRE = 0;
// Wait for frequency loop to lock.
while (!ICGS1_LOCK);
}
/**
* Hmm. I dunno if this is needed, really.
*/
#pragma INLINE
void TOSH_wait(void)
{
asm("BRN 0");
asm("BRN 0");
asm("BRN 0");
asm("BRN 0");
// asm("nop"); asm("nop");
}
// Cycle time is related to bus clock speed:
// Bus clock Cycle time
// ------------------------------
// 20 MHz 50 ns
// 16 Mhz 63 ns
// 12 Mhz 83 ns
// 8 Mhz 125 ns
// 4 Mhz 250 ns
#define TOSH_CYCLE_TIME_NS 125
#define HCS08_CYCLES_PER_US 8
// FIXED: The below functions should of course be written in asm to make
// them compiler independent. Note that they are dependent on
// MCU bus clock speed.
#pragma INLINE
void TOSH_wait_250ns(void)
{
#if HCS08_CYCLES_PER_US < 12
asm("NOP");
#if HCS08_CYCLES_PER_US > 4
asm("NOP");
#endif
#else
asm("BRN 0");
#if HCS08_CYCLES_PER_US > 12
asm("NOP");
#endif
#if HCS08_CYCLES_PER_US > 16
asm("NOP");
#endif
#endif
}
#pragma INLINE
void HCS08_short_wait_finish(void)
{
// We have already waited for 2 cycles
// During initial LDA. Make that 1us.
#if HCS08_CYCLES_PER_US == 4 || HCS08_CYCLES_PER_US == 16
// Wait for 2 cycles more.
asm("NOP");
asm("NOP");
#endif
#if HCS08_CYCLES_PER_US > 4
#if HCS08_CYCLES_PER_US > 12
// Wait for 12 cycles more
asm("BRN 0");
asm("BRN 0");
asm("BRN 0");
asm("BRN 0");
#endif
#if HCS08_CYCLES_PER_US != 16
// Wait for 6 cycles more
asm("BRN 0");
asm("BRN 0");
#endif
#if HCS08_CYCLES_PER_US == 12
// Wait for 4 cycles more
asm("BRN 0");
asm("NOP");
#endif
#endif
}
#pragma INLINE
void HCS08_short_wait_loop(void)
{
// We are going to wait for 4 cycles
// during DBNZA. Make that 1us.
#if HCS08_CYCLES_PER_US > 4
#if HCS08_CYCLES_PER_US > 12
// Wait for 12 cycles more
asm("BRN 0");
asm("BRN 0");
asm("BRN 0");
asm("BRN 0");
#endif
#if HCS08_CYCLES_PER_US != 16
// Wait for 4 cycles more
asm("BRN 0");
asm("NOP");
#endif
#if HCS08_CYCLES_PER_US == 12
// Wait for 4 cycles more
asm("BRN 0");
asm("NOP");
#endif
#endif
}
// LDA is 2 cycles and DBNZA is 4 cycles.
#define HCS08_short_uwait(u_sec) \
asm("LDA #"#u_sec); \
asm("uWait:"); \
HCS08_short_wait_loop(); \
asm("DBNZA uWait"); \
HCS08_short_wait_finish();
// The if is resolved at compile time, when u is constant.
#define TOSH_short_uwait(u) \
if ((u)==1) { \
HCS08_short_wait_loop(); \
asm("NOP"); \
asm("BRA uWaitDone"); \
} \
HCS08_short_uwait(u-1) \
asm("uWaitDone:");
// TOSH_long_uwait valid only for 4 u_sec or longer
// Shorter wait times will wait 1.6us regardless of u_sec.
#pragma NO_INLINE // timing depends on call/return
void TOSH_long_uwait( unsigned int u_sec )
{
/*
0000 87 PSHA ; A: 2 cycles
0001 89 PSHX ; A: 2 cycles
0002 8b PSHH ; A: 2 cycles
164: if( u_sec >= 3 )
0003 89 PSHX ; A: 2 cycles
0004 8a PULH ; A: 2 cycles
0005 97 TAX ; A: 2 cycles
0006 650003 CPHX #3 ; A: 3 cycles
0009 2522 BCS L2D ;abs = 002d ; A: 2 cycles
165: {
166: u_sec -= 3;
000b a003 SUB #3 ; B: 2 cycles
000d 8b PSHH ; B: 2 cycles
000e 95 TSX ; B: 2 cycles
000f e703 STA 3,X ; B: 3 cycles
0011 86 PULA ; B: 3 cycles
0012 a200 SBC #0 ; B: 2 cycles
0014 e702 STA 2,X ; B: 3 cycles
167: {
168: unsigned char u = (u_sec & 255);
0016 e603 LDA 3,X ; B: 3 cycles
0018 e701 STA 1,X ; B: 3 cycles
169: if( u > 0 )
001a 2702 BEQ L1E ;abs = 001e ; B: 3 cycles
170: TOSH_short_uwait( u );
001c ad00 BSR TOSH_short_uwait ; ... wait ... subtract 2 cycles
001e L1E:
171:
172: u = u_sec >> 8;
001e 95 TSX ; B: 2 cycles
001f e601 LDA 1,X ; B: 3 cycles
0021 f7 STA ,X ; B: 2 cycles
173: while( u > 0 )
0022 2006 BRA L2A ;abs = 002a ; B: 3 cycles
0024 L24:
174: {
175: TOSH_short_uwait( 255 );
0024 a6ff LDA #-1 // calcualted as part of short_wait
0026 ad00 BSR TOSH_short_uwait // ... wait ...
176: u--;
0028 95 TSX ; C: 2 cycles
0029 7a DEC ,X ; C: 4 cycles
002a L2A:
002a 7d TST ,X ; C: 3 cycles
002b 26f7 BNE L24 ;abs = 0024 ; C: 3 cycles
002d L2D:
177: }
178: }
179: }
180: }
002d a703 AIS #3 ; A: 2 cycles
002f 81 RTS ; A: 6 cycles
*/
// A total: 25 cycles
// B total: 34 cycles
// C total: 12 cycles
if( u_sec >= 4 )
{
u_sec -= 4;
{
unsigned char u = (u_sec & 255);
if( u > 0 )
TOSH_short_uwait( u );
u = u_sec >> 8;
while( u > 0 )
{
TOSH_short_uwait( 255 );
u--;
// loop overhead from C is 12 cycles, add 4 more to get 1us total
asm("nop"); asm("nop"); asm("nop"); asm("nop");
}
}
// Total overhead from A and B is 59 cycles, but don't add any more,
// because just the BSR to get here is 5 cycles.
}
}
// The only observed use of TOSH_uwait is with constants, so this selection
// will be resolved at compile time.
#define TOSH_uwait(u) (((u)<=255) ? TOSH_short_uwait(u) : TOSH_long_uwait(u))
/*
#pragma INLINE
void TOSH_uwait( unsigned int u_sec )
{
if( (u_sec >> 8) == 0 ) TOSH_short_uwait( u_sec & 255 );
else TOSH_long_uwait( u_sec );
}
*/
//inline void __nesc_disable_interrupt() { hcs08_disable_interrupt(); }
//inline void __nesc_enable_interrupt() { hcs08_enable_interrupt(); }
#define __nesc_disable_interrupt() hcs08_disable_interrupt()
#define __nesc_enable_interrupt() hcs08_enable_interrupt()
/*
// Force the spontaneous attribute to prevent inlining by nesc.
// And, if the hcs08 compiler tries to inline it, it screws it up, badly.
unsigned char getCCR() __attribute__ ((spontaneous, noinline))
{
asm( "TPA" );
asm( "RTS" );
// This spurious return will be removed by the compiler and eliminates
// warnings and errors about no return statement.
return 0;
}
*/
// this code is safer, even though the asm for it is more ugly
inline unsigned char getCCR()
{
// MBD: We initialize to 0 in order to get rid of warnings about
// this variable not beeing initialized. We do not make it static however
// as we wish for it to be on the stack. I guess.
unsigned char ccr = 0;
asm( "TPA" );
asm( "STA ccr" );
return ccr;
}
typedef unsigned char __nesc_atomic_t;
inline __nesc_atomic_t __nesc_atomic_start(void)
{
__nesc_atomic_t result = getCCR();
__nesc_disable_interrupt();
return result;
}
inline void __nesc_atomic_end( __nesc_atomic_t oldCCR )
{
// 0x08 is the interrupt *mask* in the CCR
// which means interrupts are enabled when it's 0
if( (oldCCR & 0x08) == 0 )
__nesc_enable_interrupt();
}
#define HCS08_PORT(port, type, bit) PT##port##type##_PT##port##type##bit
#define TOSH_ASSIGN_PIN(name, port, bit) \
void TOSH_SET_##name##_PIN() { HCS08_PORT(port,D,bit) = 1; } \
void TOSH_CLR_##name##_PIN() { HCS08_PORT(port,D,bit) = 0; } \
uint8_t TOSH_READ_##name##_PIN() { return HCS08_PORT(port,D,bit); } \
void TOSH_MAKE_##name##_OUTPUT() { HCS08_PORT(port,DD,bit) = 1; } \
void TOSH_MAKE_##name##_INPUT() { HCS08_PORT(port,DD,bit) = 0; } \
void TOSH_PULLUP_##name##_ENABLE() { HCS08_PORT(port,PE,bit) = 1; } \
void TOSH_PULLUP_##name##_DISABLE() { HCS08_PORT(port,PE,bit) = 0; }
typedef uint8_t mcu_power_t;
enum {
HCS08_POWER_WAIT = 0,
HCS08_POWER_STOP3 = 1,
HCS08_POWER_STOP2 = 2,
HCS08_POWER_STOP1 = 3,
};
/* Combine function. */
mcu_power_t mcombine(mcu_power_t m1, mcu_power_t m2) {
return (m1 < m2)? m1: m2;
}
#endif//_H_hcs08hardware_h
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/daq/calibrate_magic.c | <reponame>tinyos-io/tinyos-3.x-contrib
/**
* Calibration program.
*
* Does the same as DEMO19.C
*
* In order to calibrate the board, perform the following steps:
*
* Step 1: Apply 0V to channel 0
* Step 2: Apply 4.996V to channel 1
* Step 3: Apply 4.996mV to channel 2
* Step 4: Adjust VR101 until CAL:0 = 0x7FF or 0x800.
* Step 5: Adjust VR100 until CAL:1 = 0xFFE or 0xFFF.
* Step 6: Repeat step 4 and 5 until both values are fine.
* Step 7: Adjust VR2 until CAL:2 = 0x000 or 0x001.
* Step 8: Adjust VR1 until CAL:3 = 0xFFE or 0xFFF.
*
*/
#include <stdio.h>
#include <curses.h>
#include <signal.h>
#include <stdlib.h>
#include "daq_lib.h"
void sigint(int signum)
{
endwin();
exit(0);
}
struct config {
int channel;
daq_gain_t gain;
daq_range_t range;
};
struct config cfg[4] = { { 0, DG_10, DR_BIPOL5V },
{ 8, DG_1, DR_BIPOL10V },
{ 24, DG_10, DR_BIPOL5V },
{ 16, DG_1, DR_BIPOL10V } };
int main(int argc, char *argv[])
{
daq_card_t daq;
int count = 0;
int res;
int i;
struct sigaction act;
if (argc != 2) {
fprintf(stderr, "Too few arguments\n");
return 1;
}
if (daq_open(argv[1], &daq)) {
perror("Error opening daq device");
return 1;
}
/* Setup signal handler */
act.sa_handler = sigint;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGINT, &act, 0);
initscr();
nonl();
cbreak();
noecho();
move(1,1);
printw("A/D Calibration Program:\n");
printw("step 1: apply 0V to channel 0.\n");
printw("step 2: apply 4.996V to channel 1.\n");
printw("step 3: apply 4.996mV to channel 2.\n");
printw("step 4: adjust VR101 until CAL:0 = 0x7ff or 0x800.\n");
printw("step 5: adjust VR100 until CAL:1 = 0xffe or 0xfff.\n");
printw("step 6: repeat step 4 and step 5 until all OK.\n");
printw("step 7: adjust VR2 until CAL:2 = 0x000 or 0x001.\n");
printw("step 8: adjust VR1 until CAL:3 = 0xffe or 0xfff.\n");
/* Setup the scan */
if (daq_clear_scan(&daq)) {
perror("Error clearing the scan");
return 1;
}
res = 0;
for (i = 0; i < 4; ++i)
res += daq_add_scan(&daq, cfg[i].channel, cfg[i].gain, cfg[i].range);
if (res) {
perror("Error configuring scan");
return 1;
}
if (daq_start_scan(&daq, 0xFFFF)) {
perror("Error starting scan");
return 1;
}
while(1) {
uint16_t sample;
move(11, 5);
printw("Count=%ld\n", count++);
for (i = 0; i < 4; ++i) {
res = daq_get_scan_sample(&daq, &sample);
if (!res) {
move(12 + i, 5);
printw("CAL:0=0x%04x VAL:0=%02.6f\n", sample,
daq_convert_result(&daq, sample, cfg[i].gain, cfg[i].range));
} else {
endwin();
printf("(5.0V Range, CH:0) Error reading sample (Count=%d, res=%d)\n", count, res);
perror("exiting");
exit(1);
}
}
move(17, 1);
printw("Press CTRL+C to exit\n");
refresh();
}
endwin();
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | berkeley/quanto/tos/chips/cc2420/CC2420PowerStates.h | #ifndef _CC2420POWERSTATES_H
#define _CC2420POWERSTATES_H
#define SET_BITS(name, value) \
setBits(name##_LEN, name##_OFF, value)
#define LEN2MASK(name) ((1 << ((name))) - 1)
typedef uint16_t powerstate_t;
typedef union {
powerstate_t state;
struct {
unsigned int tx_pwr: 5,
unsigned int :3,
unsigned int starting: 1,
unsigned int listen : 1,
unsigned int rx : 1,
unsigned int tx : 1,
unsigned int stopping: 1,
unsigned int rx_fifo : 1,
unsigned int tx_fifo : 1,
unsigned int :1,
}
} cc2420_powerstate_t;
enum {
RADIO_TX_PWR_LEN = 5,
RADIO_TX_PWR_OFF = 0,
RADIO_TX_PWR_MASK = LEN2MASK(RADIO_TX_PWR_LEN),
};
#endif
|
tinyos-io/tinyos-3.x-contrib | rincon/tools/ft232r/d2xx/spi.c | <reponame>tinyos-io/tinyos-3.x-contrib<gh_stars>1-10
/***********************************************************************
* spi.c -- umph spi module
*/
#include <Python.h>
typedef unsigned char uc;
typedef unsigned long ul;
#define QSIZE 32768
typedef struct spi_state {
uc spien, rst, sck, mosi, miso, val;
ul nQ;
uc *Q;
PyObject *read, *write;
} spi_state_t;
static char c;
static void _del(void *obj, void *desc) {
if (desc == &c) {
spi_state_t *sp = (spi_state_t *) obj;
Py_XDECREF(sp->read);
Py_XDECREF(sp->write);
PyMem_Free(sp->Q);
PyMem_Free(obj);
}
}
static PyObject *new(void) {
spi_state_t *sp;
PyObject *o;
if ((sp = PyMem_Malloc(sizeof(spi_state_t))) == NULL)
return PyErr_NoMemory();
memset(sp, 0, sizeof(spi_state_t));
if ((sp->Q = PyMem_Malloc(QSIZE * sizeof(uc))) == NULL) {
PyMem_Free(sp);
return PyErr_NoMemory();
}
if ((o = PyCObject_FromVoidPtrAndDesc(sp, &c, _del)) == NULL) {
PyMem_Free(sp->Q);
PyMem_Free(sp);
return NULL;
}
return o;
}
static spi_state_t *get(PyObject *o) {
if (!PyCObject_Check(o)) {
PyErr_SetString(PyExc_TypeError, "spi_state_t expected");
return NULL;
}
if (PyCObject_GetDesc(o) != &c) {
PyErr_SetString(PyExc_TypeError, "spi_state_t expected");
return NULL;
}
return (spi_state_t *) PyCObject_AsVoidPtr(o);
}
static PyObject *alloc(PyObject *self, PyObject *args) {
PyObject *so, *read, *write;
spi_state_t *sp;
int spien, rst, sck, mosi, miso, tmp;
if (!PyArg_ParseTuple(args, "iiiiiOO",
&spien, &rst, &sck, &mosi, &miso,
&read, &write))
return NULL;
if ((so = new()) == NULL)
return NULL;
if ((sp = get(so)) == NULL)
goto bad;
if (!PyCallable_Check(read)) {
PyErr_SetString(PyExc_TypeError, "expected callable");
goto bad;
}
Py_INCREF(read);
sp->read = read;
if (!PyCallable_Check(write)) {
PyErr_SetString(PyExc_TypeError, "expected callable");
goto bad;
}
Py_INCREF(write);
sp->write = write;
tmp = spien;
if ((tmp & (tmp - 1)) || (tmp & ~0xff)) {
PyErr_SetString(PyExc_ValueError, "Expected 1-bit mask");
goto bad;
}
sp->spien = tmp;
tmp = rst;
if ((tmp & (tmp - 1)) || (tmp & ~0xff)) {
PyErr_SetString(PyExc_ValueError, "Expected 1-bit mask");
goto bad;
}
sp->rst = tmp;
tmp = sck;
if (!tmp || (tmp & (tmp - 1)) || (tmp & ~0xff)) {
PyErr_SetString(PyExc_ValueError, "Expected 1-bit mask");
goto bad;
}
sp->sck = tmp;
tmp = mosi;
if (!tmp || (tmp & (tmp - 1)) || (tmp & ~0xff)) {
PyErr_SetString(PyExc_ValueError, "Expected 1-bit mask");
goto bad;
}
sp->mosi = tmp;
tmp = miso;
if (!tmp || (tmp & (tmp - 1)) || (tmp & ~0xff)) {
PyErr_SetString(PyExc_ValueError, "Expected 1-bit mask");
goto bad;
}
sp->miso = tmp;
sp->val = 0;
sp->nQ = 0;
return so;
bad:
Py_DECREF(so);
return NULL;
}
PyDoc_STRVAR(dalloc,
"obj = alloc(spien, rst, sck, mosi, miso, read, write)\n"
"\n"
"create a spi object.\n");
static PyObject *spien(PyObject *self, PyObject *args) {
PyObject *so;
spi_state_t *sp;
int val;
if (!PyArg_ParseTuple(args, "Oi", &so, &val))
return NULL;
if ((sp = get(so)) == NULL)
return NULL;
if (val)
sp->val |= sp->spien;
else
sp->val &= ~sp->spien;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(dspien,
"spien(spi, value)\n"
"\n"
"set SPI_EN value.\n");
static PyObject *rst(PyObject *self, PyObject *args) {
PyObject *so;
spi_state_t *sp;
int val;
if (!PyArg_ParseTuple(args, "Oi", &so, &val))
return NULL;
if ((sp = get(so)) == NULL)
return NULL;
if (val)
sp->val |= sp->rst;
else
sp->val &= ~sp->rst;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(drst,
"rst(spi, value)\n"
"\n"
"set SPI_EN value.\n");
static PyObject *sck(PyObject *self, PyObject *args) {
PyObject *so;
spi_state_t *sp;
int val;
if (!PyArg_ParseTuple(args, "Oi", &so, &val))
return NULL;
if ((sp = get(so)) == NULL)
return NULL;
if (val)
sp->val |= sp->sck;
else
sp->val &= ~sp->sck;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(dsck,
"sck(spi, value)\n"
"\n"
"set SPI_EN value.\n");
static PyObject *mosi(PyObject *self, PyObject *args) {
PyObject *so;
spi_state_t *sp;
int val;
if (!PyArg_ParseTuple(args, "Oi", &so, &val))
return NULL;
if ((sp = get(so)) == NULL)
return NULL;
if (val)
sp->val |= sp->mosi;
else
sp->val &= ~sp->mosi;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(dmosi,
"mosi(spi, value)\n"
"\n"
"set SPI_EN value.\n");
static PyObject *miso(PyObject *self, PyObject *args) {
PyObject *so;
spi_state_t *sp;
int val;
if (!PyArg_ParseTuple(args, "Oi", &so, &val))
return NULL;
if ((sp = get(so)) == NULL)
return NULL;
if (val)
sp->val |= sp->miso;
else
sp->val &= ~sp->miso;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(dmiso,
"miso(spi, value)\n"
"\n"
"set SPI_EN value.\n");
/*** write Q to device */
static int wr(spi_state_t *sp) {
PyObject *rc;
if (!sp->nQ)
return 0;
if ((rc = PyObject_CallFunction(sp->write, "s#", sp->Q, sp->nQ)) == NULL)
return -1;
Py_DECREF(rc);
sp->nQ = 0;
return 0;
}
/*** enqueue byte to device, possibly calling wr() */
static int enq(spi_state_t *sp, uc val, int f) {
sp->Q[sp->nQ++] = val;
if (f || (sp->nQ >= QSIZE))
return wr(sp);
return 0;
}
static PyObject *update(PyObject *self, PyObject *args) {
PyObject *so;
spi_state_t *sp;
int f = 0;
if (!PyArg_ParseTuple(args, "O|i", &so, &f))
return NULL;
if ((sp = get(so)) == NULL)
return NULL;
if (enq(sp, sp->val, f))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(dupdate,
"update(spi, [doFlush=False])\n"
"\n"
"enqueue spi state, possibly flushing.\n");
static PyObject *flush(PyObject *self, PyObject *args) {
PyObject *so;
spi_state_t *sp;
if (!PyArg_ParseTuple(args, "O", &so))
return NULL;
if ((sp = get(so)) == NULL)
return NULL;
if (wr(sp))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(dflush,
"flush(spi)\n"
"\n"
"flush all pending writes to the bus.\n");
/*** read device miso */
static int bit(spi_state_t *sp) {
PyObject *rc;
int ret;
/*** flush */
if (wr(sp))
return -1;
/*** read bus */
if ((rc = PyObject_CallFunction(sp->read, NULL)) == NULL)
return -1;
if (!PyInt_CheckExact(rc)) {
PyErr_SetString(PyExc_TypeError, "int expected");
Py_DECREF(rc);
return -1;
}
ret = PyInt_AsLong(rc);
Py_DECREF(rc);
return (ret & sp->miso) ? 1 : 0;
}
static PyObject *rbit(PyObject *self, PyObject *args) {
PyObject *so;
spi_state_t *sp;
int ret;
if (!PyArg_ParseTuple(args, "O", &so))
return NULL;
if ((sp = get(so)) == NULL)
return NULL;
if ((ret = bit(sp)) < 0)
return NULL;
return PyInt_FromLong(ret);
}
PyDoc_STRVAR(drbit,
"bit = rbit(spi)\n"
"\n"
"return state of miso line.\n");
static PyObject *byte(PyObject *self, PyObject *args) {
PyObject *so;
spi_state_t *sp;
int i, val, r = 0, ret = 0;
if (!PyArg_ParseTuple(args, "Oi|i", &so, &val, &r))
return NULL;
if ((sp = get(so)) == NULL)
return NULL;
for (i = 0; i < 8; i++) {
int tmp;
/*** read bit (or not) */
if (r) {
if ((tmp = bit(sp)) < 0)
return NULL;
} else {
tmp = 0;
}
ret = (ret << 1) | tmp;
/*** set mosi from val.7 */
if (val & 0x80) {
sp->val |= sp->mosi;
} else {
sp->val &= ~sp->mosi;
}
val = (val & 0x7f) << 1;
/*** sck high */
sp->val |= sp->sck;
/*** enqueue bus state */
if (enq(sp, sp->val, 0))
return NULL;
/*** sck low */
sp->val &= ~sp->sck;
/*** enqueue bus state */
if (enq(sp, sp->val, 0))
return NULL;
}
/*** flush if reading */
if (r && wr(sp))
return NULL;
return PyInt_FromLong(ret);
}
PyDoc_STRVAR(dbyte,
"ret = byte(spi, value, [doRead=False])\n"
"\n"
"write value to the bus and return\n"
"the value read: 0 if doRead is False;\n"
"otherwise, what the bus returns.\n");
static PyMethodDef methods[] = {
{ "alloc", (PyCFunction) alloc, METH_VARARGS, dalloc },
{ "spien", (PyCFunction) spien, METH_VARARGS, dspien },
{ "rst", (PyCFunction) rst, METH_VARARGS, drst },
{ "sck", (PyCFunction) sck, METH_VARARGS, dsck },
{ "mosi", (PyCFunction) mosi, METH_VARARGS, dmosi },
{ "miso", (PyCFunction) miso, METH_VARARGS, dmiso },
{ "update", (PyCFunction) update, METH_VARARGS, dupdate },
{ "flush", (PyCFunction) flush, METH_VARARGS, dflush },
{ "rbit", (PyCFunction) rbit, METH_VARARGS, drbit },
{ "byte", (PyCFunction) byte, METH_VARARGS, dbyte },
{ NULL, NULL }
};
PyDoc_STRVAR(docs,
"See the function docs for details.\n");
PyMODINIT_FUNC
init_spi(void) {
Py_InitModule3("_spi", methods, docs);
}
/*** EOF spi.c */
|
tinyos-io/tinyos-3.x-contrib | tcd/powertossim-z/tinyos_files/tinyos-2.0.2/tos/chips/atm128/Atm128Clock.h | // $Id: Atm128Clock.h,v 1.1 2014/11/26 19:31:33 carbajor Exp $
/*
* 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>>
#ifndef _H_ATM128CLOCK_H
#define _H_ATM128CLOCK_H
//====================== Oscillators ==================================
/* Timer Clock Select -- set via Fuses only through ISP */
enum {
ATM128_CKSEL_EXT_CLK = 0, //!< External clock source
ATM128_CKSEL_INT_1MHZ = 1, //!< Internal RC oscillator
ATM128_CKSEL_INT_2MHZ,
ATM128_CKSEL_INT_4MHZ,
ATM128_CKSEL_INT_8MHZ,
ATM128_CKSEL_EXT_RC_1MHZ = 5, //!< External RC oscillator
ATM128_CKSEL_EXT_RC_3MHZ,
ATM128_CKSEL_EXT_RC_8MHZ,
ATM128_CKSEL_EXT_RC_12MHZ,
ATM128_CKSEL_EXT_CRYSTAL = 9, //!< External low freq crystal
ATM128_CKSEL_EXT_RES_1MHZ = 10, //!< External resonator
ATM128_CKSEL_EXT_RES_3MHZ,
ATM128_CKSEL_EXT_RES_8MHZ
};
/*
* Calibration Register for Internal Oscillator
*
* OSCCAL Min Freq Max Freq
* 0x00 50% 100%
* 0x7F 75% 150%
* 0xFF 100% 200%
*/
typedef uint8_t Atm128_OSCCAL_t; //!< Internal Oscillator Calibration Register
/* 8-bit Clock Divider Register */
typedef struct
{
uint8_t xdiven : 1; //!< Enable clock divider
uint8_t xdiv : 7; //!< fCLK = Source Clock / 129 - xdiv
} Atm128ClockDivider_t;
typedef Atm128ClockDivider_t Atm128_XTAL_t; //!< Asynchronous Clock Divider
#endif //_H_ATM128CLOCK_H
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/compression/buffer.h | <reponame>tinyos-io/tinyos-3.x-contrib
/**************************************************************************
*
* buffer.h
*
* An implementation of the most basic buffer manipulation functions,
* needed for the compression algorithms.
*
* This file is licensed under the GNU GPL.
*
* (C) 2005, <NAME> <<EMAIL>>
*
*/
#ifndef _BUFFER_H
#define _BUFFER_H
#ifndef __MSP430__
#include <inttypes.h>
#endif
#define MEMBUFSIZE 256
/*
The reset_buffer function initializes the pointers to the
buffer. This function must be called before write_bits and bits_left.
*/
void reset_buffer();
uint8_t *get_unwritten();
uint8_t *get_buffer();
/*
bits_left() returns the number of bits left in the memory buffer.
*/
uint16_t bits_left();
/*
write_bits writes at most 8 bits of data to the memory buffer.
*/
void write_bits(uint8_t data, uint8_t len);
#endif
|
tinyos-io/tinyos-3.x-contrib | uob/tossdr/ucla/gnuradio-802.15.4-demodulation/sos/config/ping/ping_app.c | <reponame>tinyos-io/tinyos-3.x-contrib
#include <sos.h>
/**
* Must also include the header file that defines the
* ping_get_header() function.
*/
mod_header_ptr ping_get_header();
mod_header_ptr loader_get_header();
/**
* application start
* This function is called once at the end od SOS initialization
*/
void sos_start(void)
{
ker_register_module(ping_get_header());
ker_register_module(loader_get_header());
}
|
tinyos-io/tinyos-3.x-contrib | kasetsart/tos/chips/atm328/atm328const.h | <reponame>tinyos-io/tinyos-3.x-contrib
/**
* 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 ATmega328 version of these types and functions.
*
* @notes
* This file is modified from
* <code>tinyos-2.1.0/tos/chips/atm128/atm128const.h</code>
*
* @author
* <NAME> (<EMAIL>)
*/
#ifndef ATMEGA328CONST_H
#define ATMEGA328CONST_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))
#endif
|
tinyos-io/tinyos-3.x-contrib | ethz/nodule/tos/chips/at32uc3b/uart/at32uc3b_uart.h | /* $Id: at32uc3b_uart.h,v 1.1 2008/03/09 16:36:18 yuecelm Exp $ */
/* @author <NAME> <<EMAIL>> */
#ifndef __AT32UC3B_UART_H__
#define __AT32UC3B_UART_H__
#include "at32uc3b.h"
#define get_avr32_usart_baseaddress(usart) \
((usart == 0) ? AVR32_USART0_ADDRESS : ((usart == 1) ? AVR32_USART1_ADDRESS : ((usart == 2) ? AVR32_USART2_ADDRESS : AVR32_USART0_ADDRESS )))
#ifndef AVR32_USART0_ALTERNATIVE_GPIO_MAPPING
#define AVR32_GPIO_PERIPHERAL_FUNC_USART0 AVR32_GPIO_PERIPHERAL_FUNC_C
#else
#define AVR32_GPIO_PERIPHERAL_FUNC_USART0 AVR32_GPIO_PERIPHERAL_FUNC_A
#endif
#ifndef AVR32_USART1_ALTERNATIVE_GPIO_MAPPING
#define AVR32_GPIO_PERIPHERAL_FUNC_USART1 AVR32_GPIO_PERIPHERAL_FUNC_A
#else
#define AVR32_GPIO_PERIPHERAL_FUNC_USART1 AVR32_GPIO_PERIPHERAL_FUNC_C
#endif
#ifndef AVR32_USART2_ALTERNATIVE_GPIO_MAPPING
#define AVR32_GPIO_PERIPHERAL_FUNC_USART2 AVR32_GPIO_PERIPHERAL_FUNC_B
#else
#define AVR32_GPIO_PERIPHERAL_FUNC_USART2 AVR32_GPIO_PERIPHERAL_FUNC_C
#endif
#define get_avr32_usart_peripheral_function(usart) \
((usart == 0) ? AVR32_GPIO_PERIPHERAL_FUNC_USART0 : ((usart == 1) ? AVR32_GPIO_PERIPHERAL_FUNC_USART1 : \
((usart == 2) ? AVR32_GPIO_PERIPHERAL_FUNC_USART2 : AVR32_GPIO_PERIPHERAL_FUNC_USART0 )))
#define get_avr32_usart_pbamask_offset(usart) \
((usart == 0) ? AVR32_PBAMASK_USART0_OFFSET : ((usart == 1) ? AVR32_PBAMASK_USART1_OFFSET : \
((usart == 2) ? AVR32_PBAMASK_USART2_OFFSET : AVR32_PBAMASK_USART0_OFFSET )))
#endif /*__AT32UC3B_UART_H__*/
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/mica2dot/timerdefs.h | #ifndef TIMERDEFS
#define TIMERDEFS
enum
{
TIMERRES = (uint32_t)500000
};
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/stargate/rt_intercomm.c | <filename>eon/eon/src/runtime/stargate/rt_intercomm.c<gh_stars>1-10
#include "sfaccess/tinystream.h"
#include "rt_intercomm.h"
#include "../mMarsh.h"
pthread_t icommthread;
bool icomm_abort = FALSE;
int icomm_cid = 0;
void *icomm_routine(void *arg)
{
icomm_cid = tinystream_connect();
if (icomm_cid == RELY_IDX_INVALID)
{
//error reporting
return;
}
while (!icomm_abort)
{
uint16_t nodeid;
int err;
err = unmarshall_start(icomm_cid, &nodeid);
if (icomm_abort)
{
dbg(APP,"Abort\n");
break;
}
if (err)
{
dbg(APP,"Marshalling error! Abort!\n");
icomm_abort = TRUE;
break;
}
//good nodeid --call appropriate unmarshaller
err = UnmarshallByID(icomm_cid, nodeid);
if (err)
{
dbg(APP,"Unmarshalling error on node(%i)! Abort!\n",nodeid);
icomm_abort = TRUE;
}
}
//tinystream_close();
return;
}
int intercomm_start(short port)
{
int result;
icomm_abort = FALSE;
result = tinystream_init("localhost", port);
if (result < 0)
{
dbg(APP,"Could not open tinystream on port:%i\n",port);
return -1;
}
//spawn recv thread.
if(pthread_create(&icommthread, NULL, icomm_routine, NULL))
return -1;
return 0;
}
int intercomm_stop()
{
icomm_abort = TRUE;
tinystream_close();
pthread_join(icommthread, NULL);
dbg(APP,"intercomm stopped...");
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/lib/bittable/BitTable.h | <reponame>tinyos-io/tinyos-3.x-contrib
#ifndef BITTABLE_H
#define BITTABLE_H
#ifndef SIZE_OF_BIT_TABLE_IN_BYTES
#define SIZE_OF_BIT_TABLE_IN_BYTES 4 // 32 bits
#endif
#ifndef TOTAL_BIT_TABLE_ELEMENTS
#define TOTAL_BIT_TABLE_ELEMENTS SIZE_OF_BIT_TABLE_IN_BYTES * 8
#endif
typedef struct bit_table_t {
uint8_t data[SIZE_OF_BIT_TABLE_IN_BYTES];
} bit_table_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/stargate/sfaccess/teloscomm.h | #ifndef _TELOSCOMM_H_
#define _TELOSCOMM_H_
#include <stdint.h>
#include <stdarg.h>
#include <stdio.h>
#define DEBUG
void hton_int16(uint8_t *buf, int16_t data);
void hton_int32(uint8_t *buf, int32_t data);
void hton_uint16(uint8_t *buf, uint16_t data);
void hton_uint32(uint8_t *buf, uint32_t data);
void ntoh_int16(uint8_t *buf, int16_t *data);
void ntoh_int32(uint8_t *buf, int32_t *data);
void ntoh_uint16(uint8_t *buf, uint16_t *data);
void ntoh_uint32(uint8_t *buf, uint32_t *data);
int dbg(int level, const char* format, ...);
enum {
TSRC = 0,
TRELY = 1,
APP = 2
};
#endif
|
tinyos-io/tinyos-3.x-contrib | gems/ttsp/tinyos/apps/tests/TestTtsp/TestTtsp.h | <reponame>tinyos-io/tinyos-3.x-contrib
#ifndef TEST_TTSP_H
#define TEST_TTSP_H
typedef nx_struct TestTtspMsg {
nx_uint16_t srcAddr;
nx_uint32_t globalTime;
nx_uint32_t localTime;
nx_int32_t offset;
nx_uint32_t beaconId;
nx_uint16_t rootId;
nx_uint32_t syncPeriod;
nx_uint32_t maxPrecisionError;
} TestTtspMsg_t;
typedef nx_struct BeaconTtspMsg
{
nx_uint16_t srcAddr;
} BeaconTtspMsg_t;
enum
{
AM_TESTTTSPMSG = 140
};
#endif |
tinyos-io/tinyos-3.x-contrib | cotsbots/tos/lib/BeepDiffusionMsg.h | <filename>cotsbots/tos/lib/BeepDiffusionMsg.h<gh_stars>1-10
/* tab:4
*
*
* "Copyright (c) 2000-2002 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."
*
*/
/*
* Authors: <NAME>
* Date last modified: 9/25/02
*
*/
/* Message types used by BeepDiffusion. */
typedef struct BeepDiffusionMsg {
uint16_t beeperID;
} BeepDiffusionMsg;
typedef struct BeepDiffusionResetMsg {
int16_t tickLength;
} BeepDiffusionResetMsg;
enum {
AM_BEEPDIFFUSIONMSG = 41,
AM_BEEPDIFFUSIONRESETMSG = 42
};
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/stargate/sfaccess/Semaphore.c | <reponame>tinyos-io/tinyos-3.x-contrib
/****************************************************************************\
*
* Written by
* <NAME> (<EMAIL>)
* at the Distributed Problem Solving Lab
* Department of Computer Science, University of Massachusetts,
* Amherst, MA 01003
*
* Copyright (c) 1995 UMASS CS Dept. All rights are reserved.
*
* Development of this code was partially supported by:
* ONR grant N00014-92-J-1450
* NSF contract CDA-8922572
*
* ---------------------------------------------------------------------------
*
* This code is free software; you can redistribute it and/or modify it.
* However, this header must remain intact and unchanged. Additional
* information may be appended after this header. Publications based on
* this code must also include an appropriate reference.
*
* This code 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.
*
\****************************************************************************/
#include "Semaphore.h"
/*
* function must be called prior to semaphore use.
*
*/
void
semaphore_init (Semaphore * s)
{
s->v = 1;
if (pthread_mutex_init (&(s->mutex), pthread_mutexattr_default) == -1)
do_error ("Error setting up semaphore mutex");
if (pthread_cond_init (&(s->cond), pthread_condattr_default) == -1)
do_error ("Error setting up semaphore condition signal");
}
/*
* function should be called when there is no longer a need for
* the semaphore.
*
*/
void
semaphore_destroy (Semaphore * s)
{
if (pthread_mutex_destroy (&(s->mutex)) == -1)
do_error ("Error destroying semaphore mutex");
if (pthread_cond_destroy (&(s->cond)) == -1)
do_error ("Error destroying semaphore condition signal");
}
/*
* function increments the semaphore and signals any threads that
* are blocked waiting a change in the semaphore.
*
*/
int
semaphore_up (Semaphore * s)
{
int value_after_op;
tw_pthread_mutex_lock (&(s->mutex));
(s->v)++;
value_after_op = s->v;
tw_pthread_mutex_unlock (&(s->mutex));
tw_pthread_cond_signal (&(s->cond));
return (value_after_op);
}
/*
* function decrements the semaphore and blocks if the semaphore is
* <= 0 until another thread signals a change.
*
*/
int
semaphore_down (Semaphore * s)
{
int value_after_op;
tw_pthread_mutex_lock (&(s->mutex));
while (s->v <= 0)
{
tw_pthread_cond_wait (&(s->cond), &(s->mutex));
}
(s->v)--;
value_after_op = s->v;
tw_pthread_mutex_unlock (&(s->mutex));
return (value_after_op);
}
/*
* function does NOT block but simply decrements the semaphore.
* should not be used instead of down -- only for programs where
* multiple threads must up on a semaphore before another thread
* can go down, i.e., allows programmer to set the semaphore to
* a negative value prior to using it for synchronization.
*
*/
int
semaphore_decrement (Semaphore * s)
{
int value_after_op;
tw_pthread_mutex_lock (&(s->mutex));
s->v--;
value_after_op = s->v;
tw_pthread_mutex_unlock (&(s->mutex));
return (value_after_op);
}
/*
* function returns the value of the semaphore at the time the
* critical section is accessed. obviously the value is not guarenteed
* after the function unlocks the critical section. provided only
* for casual debugging, a better approach is for the programmar to
* protect one semaphore with another and then check its value.
* an alternative is to simply record the value returned by semaphore_up
* or semaphore_down.
*
*/
int
semaphore_value (Semaphore * s)
{
/* not for sync */
int value_after_op;
tw_pthread_mutex_lock (&(s->mutex));
value_after_op = s->v;
tw_pthread_mutex_unlock (&(s->mutex));
return (value_after_op);
}
/* -------------------------------------------------------------------- */
/* The following functions replace standard library functions in that */
/* they exit on any error returned from the system calls. Saves us */
/* from having to check each and every call above. */
/* -------------------------------------------------------------------- */
int
tw_pthread_mutex_unlock (pthread_mutex_t * m)
{
int return_value;
if ((return_value = pthread_mutex_unlock (m)) == -1)
do_error ("pthread_mutex_unlock");
return (return_value);
}
int
tw_pthread_mutex_lock (pthread_mutex_t * m)
{
int return_value;
if ((return_value = pthread_mutex_lock (m)) == -1)
do_error ("pthread_mutex_lock");
return (return_value);
}
int
tw_pthread_cond_wait (pthread_cond_t * c, pthread_mutex_t * m)
{
int return_value;
if ((return_value = pthread_cond_wait (c, m)) == -1)
do_error ("pthread_cond_wait");
return (return_value);
}
int
tw_pthread_cond_signal (pthread_cond_t * c)
{
int return_value;
if ((return_value = pthread_cond_signal (c)) == -1)
do_error ("pthread_cond_signal");
return (return_value);
}
/*
* function just prints an error message and exits
*
*/
void
do_error (char *msg)
{
perror (msg);
exit (1);
}
|
tinyos-io/tinyos-3.x-contrib | diku/common/lib/simplemac/hplcc2420.h | #ifndef HPLCC2420_H
#define HPLCC2420_H
typedef enum
{
CC_REG_SNOP =0x00,
CC_REG_SXOSCON =0x01,
CC_REG_STXCAL =0x02,
CC_REG_SRXON =0x03,
CC_REG_STXON =0x04,
CC_REG_STXONCCA =0x05,
CC_REG_SRFOFF =0x06,
CC_REG_SXOSCOFF =0x07,
CC_REG_SFLUSHRX =0x08,
CC_REG_SFLUSHTX =0x09,
CC_REG_SACK =0x0A,
CC_REG_SACKPEND =0x0B,
CC_REG_SRXDEC =0x0C,
CC_REG_STXENC =0x0D,
CC_REG_SAES =0x0E,
CC_REG_MAIN =0x10,
CC_REG_MDMCTRL0 =0x11,
CC_REG_MDMCTRL1 =0x12,
CC_REG_RSSI =0x13,
CC_REG_SYNCWORD =0x14,
CC_REG_TXCTRL =0x15,
CC_REG_RXCTRL0 =0x16,
CC_REG_RXCTRL1 =0x17,
CC_REG_FSCTRL =0x18,
CC_REG_SECCTRL0 =0x19,
CC_REG_SECCTRL1 =0x1A,
CC_REG_BATTMON =0x1B,
CC_REG_IOCFG0 =0x1C,
CC_REG_IOCFG1 =0x1D,
CC_REG_MANFIDL =0x1E,
CC_REG_MANFIDH =0x1F,
CC_REG_FSMTC =0x20,
CC_REG_MANAND =0x21,
CC_REG_MANOR =0x22,
CC_REG_AGCCTRL =0x23,
CC_REG_AGCTST0 =0x24,
CC_REG_AGCTST1 =0x25,
CC_REG_AGCTST2 =0x26,
CC_REG_FSTST0 =0x27,
CC_REG_FSTST1 =0x28,
CC_REG_FSTST2 =0x29,
CC_REG_FSTST3 =0x2A,
CC_REG_RXBPFTST =0x2B,
CC_REG_FSMSTATE =0x2C,
CC_REG_ADCTST =0x2D,
CC_REG_DACTST =0x2E,
CC_REG_TOPTST =0x2F,
CC_REG_RESERVED =0x30,
CC_REG_TXFIFO =0x3E,
CC_REG_RXFIFO =0x3F
}cc2420_reg_t;
typedef enum
{
CC_ADDR_TXFIFO =0x000,
CC_ADDR_RXFIFO =0x080,
CC_ADDR_KEY0 =0x100,
CC_ADDR_RXNONCE =0x110,
CC_ADDR_SABUF =0x120,
CC_ADDR_KEY1 =0x130,
CC_ADDR_TXNONCE =0x140,
CC_ADDR_CBCSTATE =0x150,
CC_ADDR_IEEEADDR =0x160,
CC_ADDR_PANID =0x168,
CC_ADDR_SHORTADDR =0x16A
}cc2420_addr_t;
/*#define CC2420_RSSI_VALID 0x80
#define CC2420_TX_ACTIVE 0x40*/
/*MDMCTRL0 bits*/
#define CC2420_MC0_RESERVED_FRAME_MODE 0x2000
#define CC2420_MC0_PAN_COORDINATOR 0x1000
#define CC2420_MC0_ADDR_DECODE 0x0800
#define CC2420_MC0_CCA_HYST_MASK 0x0700
#define CC2420_MC0_CCA_MODE_MASK 0x00C0
#define CC2420_MC0_CCA_MODE_RSSI 0x0040
#define CC2420_MC0_CCA_MODE_802154 0x0080
#define CC2420_MC0_CCA_MODE_BOTH 0x00C0
#define CC2420_MC0_AUTOCRC 0x0020
#define CC2420_MC0_AUTOACK 0x0010
#define CC2420_MC0_PREAMB_LEN_MASK 0x000F
/*MDMCTRL1 bits*/
#define CC2420_MC1_CORR_THR_MASK 0x07C0
#define CC2420_MC1_DEMOD_AVG_MODE 0x0020
#define CC2420_MC1_MODULATION_MODE 0x0010
#define CC2420_MC1_TX_MODE_MASK 0x000C
#define CC2420_MC1_TX_MODE_BUFFERED 0x0000
#define CC2420_MC1_TX_MODE_SERIAL 0x0001
#define CC2420_MC1_TX_MODE_LOOP 0x0002
#define CC2420_MC1_RX_MODE_MASK 0x0003
#define CC2420_MC1_RX_MODE_BUFFERED 0x0000
#define CC2420_MC1_RX_MODE_SERIAL 0x0001
#define CC2420_MC1_RX_MODE_LOOP 0x0002
#define TXCTRL_INIT 0xA0FF
/* Status byte */
#define CC2420_XOSC16M_STABLE 0x40
#define CC2420_TX_UNDERFLOW 0x20
#define CC2420_ENC_BUSY 0x10
#define CC2420_TX_ACTIVE 0x08
#define CC2420_LOCK 0x04
#define CC2420_RSSI_VALID 0x02
typedef enum
{
CCA_HYST_0DB = 0x00,
CCA_HYST_1DB = 0x01,
CCA_HYST_2DB = 0x02,
CCA_HYST_3DB = 0x03,
CCA_HYST_4DB = 0x04,
CCA_HYST_5DB = 0x05,
CCA_HYST_6DB = 0x06,
CCA_HYST_7DB = 0x07,
} cca_hyst_db_t;
typedef enum
{
LEADING_ZERO_BYTES_1 = 0x00,
LEADING_ZERO_BYTES_2 = 0x01,
LEADING_ZERO_BYTES_3 = 0x02,
LEADING_ZERO_BYTES_4 = 0x03,
LEADING_ZERO_BYTES_5 = 0x04,
LEADING_ZERO_BYTES_6 = 0x05,
LEADING_ZERO_BYTES_7 = 0x06,
LEADING_ZERO_BYTES_8 = 0x07,
LEADING_ZERO_BYTES_9 = 0x08,
LEADING_ZERO_BYTES_10 = 0x09,
LEADING_ZERO_BYTES_11 = 0x0A,
LEADING_ZERO_BYTES_12 = 0x0B,
LEADING_ZERO_BYTES_13 = 0x0C,
LEADING_ZERO_BYTES_14 = 0x0D,
LEADING_ZERO_BYTES_15 = 0x0E,
LEADING_ZERO_BYTES_16 = 0x0F,
} preamble_length_t;
typedef struct
{
preamble_length_t preamble_length : 4;
bool autoack : 1;
bool autocrc : 1;
uint8_t cca_mode : 2;
cca_hyst_db_t cca_hyst : 3;
bool adr_decode : 1;
bool pan_coordinator : 1;
bool reserved_frame_mode : 1;
uint8_t reserved : 2;
} MDMCTRL0_t;
#endif //HPLCC2420_H
|
tinyos-io/tinyos-3.x-contrib | tcd/powertossim-z/tinyos_files/tinyos-2.0.2/tos/lib/tossim/radio.c | <gh_stars>0
/*
* "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 the gain-based TOSSIM radio model.
*
* @author <NAME>
* @date Dec 10 2005
*/
#include <radio.h>
#include <sim_gain.h>
Radio::Radio() {}
Radio::~Radio() {}
void Radio::add(int src, int dest, double gain) {
sim_gain_add(src, dest, gain);
}
double Radio::gain(int src, int dest) {
return sim_gain_value(src, dest);
}
bool Radio::connected(int src, int dest) {
return sim_gain_connected(src, dest);
}
void Radio::remove(int src, int dest) {
sim_gain_remove(src, dest);
}
void Radio::setNoise(int node, double mean, double range) {
sim_gain_set_noise_floor(node, mean, range);
}
void Radio::setSensitivity(double sensitivity) {
sim_gain_set_sensitivity(sensitivity);
}
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/lib/Nmea/Nmea.h | <reponame>tinyos-io/tinyos-3.x-contrib<filename>rincon/tos/lib/Nmea/Nmea.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
*/
/**
* TODO:Add documentation here.
*
* @author <NAME>
*/
#ifndef NMEA_H
#define NMEA_H
#ifndef NMEA_MAX_LENGTH
#define NMEA_MAX_LENGTH 82
#endif
#ifndef NMEA_MAX_FIELDS
#define NMEA_MAX_FIELDS 14
#endif
enum {
NMEA_START = 0x24,//$
//NMEA_END1 = 0x0D,//CR
NMEA_END = 0x0A,//LF -- NMEA 'sentence' terminator
NMEA_DELIMETER = 0x2C,//','
NMEA_CHECKSUM_DELIM = 0x2A,//'*'
ASCII_PERIOD = 0x2E,//ASCII period '.'
ASCII_ZERO = 0x30,//ASCII zero '0'
ASCII_FIVE = 0x35,//ASCII five '5'
ASCII_NINE = 0x39,//ASCII nine '9'
ASCII_A = 0x41,//ASCII 'A'
ASCII_G = 0x47,//ASCII 'G'
ASCII_M = 0x4D,//ASCII 'M'
ASCII_P = 0x50,//ASCII 'P'
};
typedef struct nmea_raw {
uint8_t sentence[NMEA_MAX_LENGTH];
uint8_t length;//length of raw string from '$' to LF inclusive
uint8_t fields[NMEA_MAX_FIELDS];//indexes of field delimiters (',' -- commas) in string
uint8_t fieldCount;//number of fields in current string
} nmea_raw_t;
#define char2num(c) (c - ASCII_ZERO)
#define strTo2Digit(str, start) (char2num(str[start])*10 + char2num(str[start+1]))
#define strTo3Digit(str, start) (char2num(str[start])*100 + char2num(str[start+1])*10 + char2num(str[start+2]))
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/driver/set_interface.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_interface(libusb_device_t *dev, int interface, int altsetting,
int timeout)
{
NTSTATUS status = STATUS_SUCCESS;
URB *urb;
int i, config_size, tmp_size;
USB_CONFIGURATION_DESCRIPTOR *configuration_descriptor = NULL;
USB_INTERFACE_DESCRIPTOR *interface_descriptor = NULL;
USBD_INTERFACE_INFORMATION *interface_information = NULL;
DEBUG_PRINT_NL();
DEBUG_MESSAGE("set_interface(): interface %d", interface);
DEBUG_MESSAGE("set_interface(): altsetting %d", altsetting);
DEBUG_MESSAGE("set_interface(): timeout %d", timeout);
if(!dev->config.value)
{
DEBUG_ERROR("release_interface(): device is not configured");
return STATUS_INVALID_DEVICE_STATE;
}
configuration_descriptor = get_config_descriptor(dev, dev->config.value,
&config_size);
if(!configuration_descriptor)
{
DEBUG_ERROR("set_interface(): memory_allocation error");
return STATUS_NO_MEMORY;
}
interface_descriptor =
find_interface_desc(configuration_descriptor, config_size,
interface, altsetting);
if(!interface_descriptor)
{
DEBUG_ERROR("set_interface(): interface %d or altsetting %d invalid",
interface, altsetting);
ExFreePool(configuration_descriptor);
return STATUS_UNSUCCESSFUL;
}
tmp_size = sizeof(struct _URB_SELECT_INTERFACE)
+ interface_descriptor->bNumEndpoints
* sizeof(USBD_PIPE_INFORMATION);
urb = ExAllocatePool(NonPagedPool, tmp_size);
if(!urb)
{
DEBUG_ERROR("set_interface(): memory_allocation error");
ExFreePool(configuration_descriptor);
return STATUS_NO_MEMORY;
}
memset(urb, 0, tmp_size);
urb->UrbHeader.Function = URB_FUNCTION_SELECT_INTERFACE;
urb->UrbHeader.Length = (USHORT)tmp_size;
urb->UrbSelectInterface.ConfigurationHandle = dev->config.handle;
urb->UrbSelectInterface.Interface.Length =
sizeof(struct _USBD_INTERFACE_INFORMATION);
urb->UrbSelectInterface.Interface.NumberOfPipes =
interface_descriptor->bNumEndpoints;
urb->UrbSelectInterface.Interface.Length +=
interface_descriptor->bNumEndpoints
* sizeof(struct _USBD_PIPE_INFORMATION);
urb->UrbSelectInterface.Interface.InterfaceNumber = (UCHAR)interface;
urb->UrbSelectInterface.Interface.AlternateSetting = (UCHAR)altsetting;
interface_information = &urb->UrbSelectInterface.Interface;
for(i = 0; i < interface_descriptor->bNumEndpoints; i++)
{
interface_information->Pipes[i].MaximumTransferSize
= LIBUSB_MAX_READ_WRITE;
}
status = call_usbd(dev, urb, IOCTL_INTERNAL_USB_SUBMIT_URB, timeout);
if(!NT_SUCCESS(status) || !USBD_SUCCESS(urb->UrbHeader.Status))
{
DEBUG_ERROR("set_interface(): setting interface failed: status: 0x%x, "
"urb-status: 0x%x", status, urb->UrbHeader.Status);
ExFreePool(configuration_descriptor);
ExFreePool(urb);
return STATUS_UNSUCCESSFUL;
}
update_pipe_info(dev, interface_information);
ExFreePool(configuration_descriptor);
ExFreePool(urb);
return status;
}
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/compression/huffman/test.c | <filename>diku/common/tools/compression/huffman/test.c
#ifndef __AVR_ATmega128__
#define prog_uint8_t uint8_t
#endif
#include <inttypes.h>
#include <stdio.h>
#include "huffman_codes.h"
#if VALUE_BITS < 9
typedef uint8_t huffman_t;
#elif VALUE_BITS < 17
typedef uint16_t huffman_t;
#elif VALUE_BITS < 33
typedef uint32_t huffman_t;
#elif VALUE_BITS < 65
typedef uint64_t huffman_t;
#else
#error "Cannot find appropriate type for huffman_t"
#endif
struct huffman_code_t {
uint8_t bits;
huffman_t value;
};
uint8_t const *data;
uint8_t read_count; /* What we already have read of the current data */
uint16_t buffer;
static void new_position(uint16_t where)
{
uint32_t bit_to_read = (LENGTH_BITS + VALUE_BITS) * where;
uint32_t byte = bit_to_read / 8;
read_count = (8 - bit_to_read % 8);
data = huffman_code + byte;
buffer = *data++;
buffer &= (1 << read_count) - 1;
}
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;
}
void extract_code(uint16_t where, struct huffman_code_t *c)
{
uint8_t left;
new_position(where);
// Read the length
c->bits = read_bits(LENGTH_BITS) + 1;
c->value = 0;
left = VALUE_BITS;
while (left != 0) {
if (left > 8) {
uint8_t val;
c->value <<= 8;
val = read_bits(8);
c->value |= val;
left -= 8;
} else {
c->value <<= left;
c->value |= read_bits(left);
left = 0;
}
}
}
int main() {
struct huffman_code_t c;
int i;
for (i = 0; i < NUMBER_OF_HUFFMAN_CODES; i++) {
extract_code(i, &c);
printf("Bits: %d Value: %d\n", c.bits, c.value);
}
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | berkeley/quanto/tos/lib/quanto/SingleContext/SingleContext.h | <filename>berkeley/quanto/tos/lib/quanto/SingleContext/SingleContext.h
#ifndef SINGLE_CONTEXT_H
#define SINGLE_CONTEXT_H
#define SINGLE_CONTEXT_UNIQUE "Single.Context.Unique"
#endif
|
tinyos-io/tinyos-3.x-contrib | stanford-lgl/tos/chips/ov7670/ov7670.c | <filename>stanford-lgl/tos/chips/ov7670/ov7670.c
/*
* A V4L2 driver for OmniVision OV7670 cameras.
*
* Copyright 2006 One Laptop Per Child Association, Inc. Written
* by <NAME> with substantial inspiration from Mark
* McClelland's ovcamchip code.
*
* Copyright 2006-7 <NAME> <<EMAIL>>
*
* This file may be distributed under the terms of the GNU General
* Public License, version 2.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/videodev.h>
#include <media/v4l2-common.h>
#include <media/v4l2-chip-ident.h>
#include <linux/i2c.h>
MODULE_AUTHOR("<NAME> <<EMAIL>>");
MODULE_DESCRIPTION("A low-level driver for OmniVision ov7670 sensors");
MODULE_LICENSE("GPL");
/*
* Basic window sizes. These probably belong somewhere more globally
* useful.
*/
#define VGA_WIDTH 640
#define VGA_HEIGHT 480
#define QVGA_WIDTH 320
#define QVGA_HEIGHT 240
#define CIF_WIDTH 352
#define CIF_HEIGHT 288
#define QCIF_WIDTH 176
#define QCIF_HEIGHT 144
/*
* Our nominal (default) frame rate.
*/
#define OV7670_FRAME_RATE 30
/*
* The 7670 sits on i2c with ID 0x42
*/
#define OV7670_I2C_ADDR 0x42
/* Registers */
#define REG_GAIN 0x00 /* Gain lower 8 bits (rest in vref) */
#define REG_BLUE 0x01 /* blue gain */
#define REG_RED 0x02 /* red gain */
#define REG_VREF 0x03 /* Pieces of GAIN, VSTART, VSTOP */
#define REG_COM1 0x04 /* Control 1 */
#define COM1_CCIR656 0x40 /* CCIR656 enable */
#define REG_BAVE 0x05 /* U/B Average level */
#define REG_GbAVE 0x06 /* Y/Gb Average level */
#define REG_AECHH 0x07 /* AEC MS 5 bits */
#define REG_RAVE 0x08 /* V/R Average level */
#define REG_COM2 0x09 /* Control 2 */
#define COM2_SSLEEP 0x10 /* Soft sleep mode */
#define REG_PID 0x0a /* Product ID MSB */
#define REG_VER 0x0b /* Product ID LSB */
#define REG_COM3 0x0c /* Control 3 */
#define COM3_SWAP 0x40 /* Byte swap */
#define COM3_SCALEEN 0x08 /* Enable scaling */
#define COM3_DCWEN 0x04 /* Enable downsamp/crop/window */
#define REG_COM4 0x0d /* Control 4 */
#define REG_COM5 0x0e /* All "reserved" */
#define REG_COM6 0x0f /* Control 6 */
#define REG_AECH 0x10 /* More bits of AEC value */
#define REG_CLKRC 0x11 /* Clocl control */
#define CLK_EXT 0x40 /* Use external clock directly */
#define CLK_SCALE 0x3f /* Mask for internal clock scale */
#define REG_COM7 0x12 /* Control 7 */
#define COM7_RESET 0x80 /* Register reset */
#define COM7_FMT_MASK 0x38
#define COM7_FMT_VGA 0x00
#define COM7_FMT_CIF 0x20 /* CIF format */
#define COM7_FMT_QVGA 0x10 /* QVGA format */
#define COM7_FMT_QCIF 0x08 /* QCIF format */
#define COM7_RGB 0x04 /* bits 0 and 2 - RGB format */
#define COM7_YUV 0x00 /* YUV */
#define COM7_BAYER 0x01 /* Bayer format */
#define COM7_PBAYER 0x05 /* "Processed bayer" */
#define REG_COM8 0x13 /* Control 8 */
#define COM8_FASTAEC 0x80 /* Enable fast AGC/AEC */
#define COM8_AECSTEP 0x40 /* Unlimited AEC step size */
#define COM8_BFILT 0x20 /* Band filter enable */
#define COM8_AGC 0x04 /* Auto gain enable */
#define COM8_AWB 0x02 /* White balance enable */
#define COM8_AEC 0x01 /* Auto exposure enable */
#define REG_COM9 0x14 /* Control 9 - gain ceiling */
#define REG_COM10 0x15 /* Control 10 */
#define COM10_HSYNC 0x40 /* HSYNC instead of HREF */
#define COM10_PCLK_HB 0x20 /* Suppress PCLK on horiz blank */
#define COM10_HREF_REV 0x08 /* Reverse HREF */
#define COM10_VS_LEAD 0x04 /* VSYNC on clock leading edge */
#define COM10_VS_NEG 0x02 /* VSYNC negative */
#define COM10_HS_NEG 0x01 /* HSYNC negative */
#define REG_HSTART 0x17 /* Horiz start high bits */
#define REG_HSTOP 0x18 /* Horiz stop high bits */
#define REG_VSTART 0x19 /* Vert start high bits */
#define REG_VSTOP 0x1a /* Vert stop high bits */
#define REG_PSHFT 0x1b /* Pixel delay after HREF */
#define REG_MIDH 0x1c /* Manuf. ID high */
#define REG_MIDL 0x1d /* Manuf. ID low */
#define REG_MVFP 0x1e /* Mirror / vflip */
#define MVFP_MIRROR 0x20 /* Mirror image */
#define MVFP_FLIP 0x10 /* Vertical flip */
#define REG_AEW 0x24 /* AGC upper limit */
#define REG_AEB 0x25 /* AGC lower limit */
#define REG_VPT 0x26 /* AGC/AEC fast mode op region */
#define REG_HSYST 0x30 /* HSYNC rising edge delay */
#define REG_HSYEN 0x31 /* HSYNC falling edge delay */
#define REG_HREF 0x32 /* HREF pieces */
#define REG_TSLB 0x3a /* lots of stuff */
#define TSLB_YLAST 0x04 /* UYVY or VYUY - see com13 */
#define REG_COM11 0x3b /* Control 11 */
#define COM11_NIGHT 0x80 /* NIght mode enable */
#define COM11_NMFR 0x60 /* Two bit NM frame rate */
#define COM11_HZAUTO 0x10 /* Auto detect 50/60 Hz */
#define COM11_50HZ 0x08 /* Manual 50Hz select */
#define COM11_EXP 0x02
#define REG_COM12 0x3c /* Control 12 */
#define COM12_HREF 0x80 /* HREF always */
#define REG_COM13 0x3d /* Control 13 */
#define COM13_GAMMA 0x80 /* Gamma enable */
#define COM13_UVSAT 0x40 /* UV saturation auto adjustment */
#define COM13_UVSWAP 0x01 /* V before U - w/TSLB */
#define REG_COM14 0x3e /* Control 14 */
#define COM14_DCWEN 0x10 /* DCW/PCLK-scale enable */
#define REG_EDGE 0x3f /* Edge enhancement factor */
#define REG_COM15 0x40 /* Control 15 */
#define COM15_R10F0 0x00 /* Data range 10 to F0 */
#define COM15_R01FE 0x80 /* 01 to FE */
#define COM15_R00FF 0xc0 /* 00 to FF */
#define COM15_RGB565 0x10 /* RGB565 output */
#define COM15_RGB555 0x30 /* RGB555 output */
#define REG_COM16 0x41 /* Control 16 */
#define COM16_AWBGAIN 0x08 /* AWB gain enable */
#define REG_COM17 0x42 /* Control 17 */
#define COM17_AECWIN 0xc0 /* AEC window - must match COM4 */
#define COM17_CBAR 0x08 /* DSP Color bar */
/*
* This matrix defines how the colors are generated, must be
* tweaked to adjust hue and saturation.
*
* Order: v-red, v-green, v-blue, u-red, u-green, u-blue
*
* They are nine-bit signed quantities, with the sign bit
* stored in 0x58. Sign for v-red is bit 0, and up from there.
*/
#define REG_CMATRIX_BASE 0x4f
#define CMATRIX_LEN 6
#define REG_CMATRIX_SIGN 0x58
#define REG_BRIGHT 0x55 /* Brightness */
#define REG_CONTRAS 0x56 /* Contrast control */
#define REG_GFIX 0x69 /* Fix gain control */
#define REG_REG76 0x76 /* OV's name */
#define R76_BLKPCOR 0x80 /* Black pixel correction enable */
#define R76_WHTPCOR 0x40 /* White pixel correction enable */
#define REG_RGB444 0x8c /* RGB 444 control */
#define R444_ENABLE 0x02 /* Turn on RGB444, overrides 5x5 */
#define R444_RGBX 0x01 /* Empty nibble at end */
#define REG_HAECC1 0x9f /* Hist AEC/AGC control 1 */
#define REG_HAECC2 0xa0 /* Hist AEC/AGC control 2 */
#define REG_BD50MAX 0xa5 /* 50hz banding step limit */
#define REG_HAECC3 0xa6 /* Hist AEC/AGC control 3 */
#define REG_HAECC4 0xa7 /* Hist AEC/AGC control 4 */
#define REG_HAECC5 0xa8 /* Hist AEC/AGC control 5 */
#define REG_HAECC6 0xa9 /* Hist AEC/AGC control 6 */
#define REG_HAECC7 0xaa /* Hist AEC/AGC control 7 */
#define REG_BD60MAX 0xab /* 60hz banding step limit */
/*
* Information we maintain about a known sensor.
*/
struct ov7670_format_struct; /* coming later */
struct ov7670_info {
struct ov7670_format_struct *fmt; /* Current format */
unsigned char sat; /* Saturation value */
int hue; /* Hue value */
};
/*
* The default register settings, as obtained from OmniVision. There
* is really no making sense of most of these - lots of "reserved" values
* and such.
*
* These settings give VGA YUYV.
*/
struct regval_list {
unsigned char reg_num;
unsigned char value;
};
static struct regval_list ov7670_default_regs[] = {
{ REG_COM7, COM7_RESET },
/*
* Clock scale: 3 = 15fps
* 2 = 20fps
* 1 = 30fps
*/
{ REG_CLKRC, 0x1 }, /* OV: clock scale (30 fps) */
{ REG_TSLB, 0x04 }, /* OV */
{ REG_COM7, 0 }, /* VGA */
/*
* Set the hardware window. These values from OV don't entirely
* make sense - hstop is less than hstart. But they work...
*/
{ REG_HSTART, 0x13 }, { REG_HSTOP, 0x01 },
{ REG_HREF, 0xb6 }, { REG_VSTART, 0x02 },
{ REG_VSTOP, 0x7a }, { REG_VREF, 0x0a },
{ REG_COM3, 0 }, { REG_COM14, 0 },
/* Mystery scaling numbers */
{ 0x70, 0x3a }, { 0x71, 0x35 },
{ 0x72, 0x11 }, { 0x73, 0xf0 },
{ 0xa2, 0x02 }, { REG_COM10, 0x0 },
/* Gamma curve values */
{ 0x7a, 0x20 }, { 0x7b, 0x10 },
{ 0x7c, 0x1e }, { 0x7d, 0x35 },
{ 0x7e, 0x5a }, { 0x7f, 0x69 },
{ 0x80, 0x76 }, { 0x81, 0x80 },
{ 0x82, 0x88 }, { 0x83, 0x8f },
{ 0x84, 0x96 }, { 0x85, 0xa3 },
{ 0x86, 0xaf }, { 0x87, 0xc4 },
{ 0x88, 0xd7 }, { 0x89, 0xe8 },
/* AGC and AEC parameters. Note we start by disabling those features,
then turn them only after tweaking the values. */
{ REG_COM8, COM8_FASTAEC | COM8_AECSTEP | COM8_BFILT },
{ REG_GAIN, 0 }, { REG_AECH, 0 },
{ REG_COM4, 0x40 }, /* magic reserved bit */
{ REG_COM9, 0x18 }, /* 4x gain + magic rsvd bit */
{ REG_BD50MAX, 0x05 }, { REG_BD60MAX, 0x07 },
{ REG_AEW, 0x95 }, { REG_AEB, 0x33 },
{ REG_VPT, 0xe3 }, { REG_HAECC1, 0x78 },
{ REG_HAECC2, 0x68 }, { 0xa1, 0x03 }, /* magic */
{ REG_HAECC3, 0xd8 }, { REG_HAECC4, 0xd8 },
{ REG_HAECC5, 0xf0 }, { REG_HAECC6, 0x90 },
{ REG_HAECC7, 0x94 },
{ REG_COM8, COM8_FASTAEC|COM8_AECSTEP|COM8_BFILT|COM8_AGC|COM8_AEC },
/* Almost all of these are magic "reserved" values. */
{ REG_COM5, 0x61 }, { REG_COM6, 0x4b },
{ 0x16, 0x02 }, { REG_MVFP, 0x07 },
{ 0x21, 0x02 }, { 0x22, 0x91 },
{ 0x29, 0x07 }, { 0x33, 0x0b },
{ 0x35, 0x0b }, { 0x37, 0x1d },
{ 0x38, 0x71 }, { 0x39, 0x2a },
{ REG_COM12, 0x78 }, { 0x4d, 0x40 },
{ 0x4e, 0x20 }, { REG_GFIX, 0 },
{ 0x6b, 0x4a }, { 0x74, 0x10 },
{ 0x8d, 0x4f }, { 0x8e, 0 },
{ 0x8f, 0 }, { 0x90, 0 },
{ 0x91, 0 }, { 0x96, 0 },
{ 0x9a, 0 }, { 0xb0, 0x84 },
{ 0xb1, 0x0c }, { 0xb2, 0x0e },
{ 0xb3, 0x82 }, { 0xb8, 0x0a },
/* More reserved magic, some of which tweaks white balance */
{ 0x43, 0x0a }, { 0x44, 0xf0 },
{ 0x45, 0x34 }, { 0x46, 0x58 },
{ 0x47, 0x28 }, { 0x48, 0x3a },
{ 0x59, 0x88 }, { 0x5a, 0x88 },
{ 0x5b, 0x44 }, { 0x5c, 0x67 },
{ 0x5d, 0x49 }, { 0x5e, 0x0e },
{ 0x6c, 0x0a }, { 0x6d, 0x55 },
{ 0x6e, 0x11 }, { 0x6f, 0x9f }, /* "9e for advance AWB" */
{ 0x6a, 0x40 }, { REG_BLUE, 0x40 },
{ REG_RED, 0x60 },
{ REG_COM8, COM8_FASTAEC|COM8_AECSTEP|COM8_BFILT|COM8_AGC|COM8_AEC|COM8_AWB },
/* Matrix coefficients */
{ 0x4f, 0x80 }, { 0x50, 0x80 },
{ 0x51, 0 }, { 0x52, 0x22 },
{ 0x53, 0x5e }, { 0x54, 0x80 },
{ 0x58, 0x9e },
{ REG_COM16, COM16_AWBGAIN }, { REG_EDGE, 0 },
{ 0x75, 0x05 }, { 0x76, 0xe1 },
{ 0x4c, 0 }, { 0x77, 0x01 },
{ REG_COM13, 0xc3 }, { 0x4b, 0x09 },
{ 0xc9, 0x60 }, { REG_COM16, 0x38 },
{ 0x56, 0x40 },
{ 0x34, 0x11 }, { REG_COM11, COM11_EXP|COM11_HZAUTO },
{ 0xa4, 0x88 }, { 0x96, 0 },
{ 0x97, 0x30 }, { 0x98, 0x20 },
{ 0x99, 0x30 }, { 0x9a, 0x84 },
{ 0x9b, 0x29 }, { 0x9c, 0x03 },
{ 0x9d, 0x4c }, { 0x9e, 0x3f },
{ 0x78, 0x04 },
/* Extra-weird stuff. Some sort of multiplexor register */
{ 0x79, 0x01 }, { 0xc8, 0xf0 },
{ 0x79, 0x0f }, { 0xc8, 0x00 },
{ 0x79, 0x10 }, { 0xc8, 0x7e },
{ 0x79, 0x0a }, { 0xc8, 0x80 },
{ 0x79, 0x0b }, { 0xc8, 0x01 },
{ 0x79, 0x0c }, { 0xc8, 0x0f },
{ 0x79, 0x0d }, { 0xc8, 0x20 },
{ 0x79, 0x09 }, { 0xc8, 0x80 },
{ 0x79, 0x02 }, { 0xc8, 0xc0 },
{ 0x79, 0x03 }, { 0xc8, 0x40 },
{ 0x79, 0x05 }, { 0xc8, 0x30 },
{ 0x79, 0x26 },
{ 0xff, 0xff }, /* END MARKER */
};
/*
* Here we'll try to encapsulate the changes for just the output
* video format.
*
* RGB656 and YUV422 come from OV; RGB444 is homebrewed.
*
* IMPORTANT RULE: the first entry must be for COM7, see ov7670_s_fmt for why.
*/
static struct regval_list ov7670_fmt_yuv422[] = {
{ REG_COM7, 0x0 }, /* Selects YUV mode */
{ REG_RGB444, 0 }, /* No RGB444 please */
{ REG_COM1, 0 },
{ REG_COM15, COM15_R00FF },
{ REG_COM9, 0x18 }, /* 4x gain ceiling; 0x8 is reserved bit */
{ 0x4f, 0x80 }, /* "matrix coefficient 1" */
{ 0x50, 0x80 }, /* "matrix coefficient 2" */
{ 0x51, 0 }, /* vb */
{ 0x52, 0x22 }, /* "matrix coefficient 4" */
{ 0x53, 0x5e }, /* "matrix coefficient 5" */
{ 0x54, 0x80 }, /* "matrix coefficient 6" */
{ REG_COM13, COM13_GAMMA|COM13_UVSAT },
{ 0xff, 0xff },
};
static struct regval_list ov7670_fmt_rgb565[] = {
{ REG_COM7, COM7_RGB }, /* Selects RGB mode */
{ REG_RGB444, 0 }, /* No RGB444 please */
{ REG_COM1, 0x0 },
{ REG_COM15, COM15_RGB565 },
{ REG_COM9, 0x38 }, /* 16x gain ceiling; 0x8 is reserved bit */
{ 0x4f, 0xb3 }, /* "matrix coefficient 1" */
{ 0x50, 0xb3 }, /* "matrix coefficient 2" */
{ 0x51, 0 }, /* vb */
{ 0x52, 0x3d }, /* "matrix coefficient 4" */
{ 0x53, 0xa7 }, /* "matrix coefficient 5" */
{ 0x54, 0xe4 }, /* "matrix coefficient 6" */
{ REG_COM13, COM13_GAMMA|COM13_UVSAT },
{ 0xff, 0xff },
};
static struct regval_list ov7670_fmt_rgb444[] = {
{ REG_COM7, COM7_RGB }, /* Selects RGB mode */
{ REG_RGB444, R444_ENABLE }, /* Enable xxxxrrrr ggggbbbb */
{ REG_COM1, 0x40 }, /* Magic reserved bit */
{ REG_COM15, COM15_R01FE|COM15_RGB565 }, /* Data range needed? */
{ REG_COM9, 0x38 }, /* 16x gain ceiling; 0x8 is reserved bit */
{ 0x4f, 0xb3 }, /* "matrix coefficient 1" */
{ 0x50, 0xb3 }, /* "matrix coefficient 2" */
{ 0x51, 0 }, /* vb */
{ 0x52, 0x3d }, /* "matrix coefficient 4" */
{ 0x53, 0xa7 }, /* "matrix coefficient 5" */
{ 0x54, 0xe4 }, /* "matrix coefficient 6" */
{ REG_COM13, COM13_GAMMA|COM13_UVSAT|0x2 }, /* Magic rsvd bit */
{ 0xff, 0xff },
};
static struct regval_list ov7670_fmt_raw[] = {
{ REG_COM7, COM7_BAYER },
{ REG_COM13, 0x08 }, /* No gamma, magic rsvd bit */
{ REG_COM16, 0x3d }, /* Edge enhancement, denoise */
{ REG_REG76, 0xe1 }, /* Pix correction, magic rsvd */
{ 0xff, 0xff },
};
/*
* Low-level register I/O.
*/
static int ov7670_read(struct i2c_client *c, unsigned char reg,
unsigned char *value)
{
int ret;
ret = i2c_smbus_read_byte_data(c, reg);
if (ret >= 0) {
*value = (unsigned char) ret;
ret = 0;
}
return ret;
}
static int ov7670_write(struct i2c_client *c, unsigned char reg,
unsigned char value)
{
int ret = i2c_smbus_write_byte_data(c, reg, value);
if (reg == REG_COM7 && (value & COM7_RESET))
msleep(2); /* Wait for reset to run */
return ret;
}
/*
* Write a list of register settings; ff/ff stops the process.
*/
static int ov7670_write_array(struct i2c_client *c, struct regval_list *vals)
{
while (vals->reg_num != 0xff || vals->value != 0xff) {
int ret = ov7670_write(c, vals->reg_num, vals->value);
if (ret < 0)
return ret;
vals++;
}
return 0;
}
/*
* Stuff that knows about the sensor.
*/
static void ov7670_reset(struct i2c_client *client)
{
ov7670_write(client, REG_COM7, COM7_RESET);
msleep(1);
}
static int ov7670_init(struct i2c_client *client)
{
return ov7670_write_array(client, ov7670_default_regs);
}
static int ov7670_detect(struct i2c_client *client)
{
unsigned char v;
int ret;
ret = ov7670_init(client);
if (ret < 0)
return ret;
ret = ov7670_read(client, REG_MIDH, &v);
if (ret < 0)
return ret;
if (v != 0x7f) /* OV manuf. id. */
return -ENODEV;
ret = ov7670_read(client, REG_MIDL, &v);
if (ret < 0)
return ret;
if (v != 0xa2)
return -ENODEV;
/*
* OK, we know we have an OmniVision chip...but which one?
*/
ret = ov7670_read(client, REG_PID, &v);
if (ret < 0)
return ret;
if (v != 0x76) /* PID + VER = 0x76 / 0x73 */
return -ENODEV;
ret = ov7670_read(client, REG_VER, &v);
if (ret < 0)
return ret;
if (v != 0x73) /* PID + VER = 0x76 / 0x73 */
return -ENODEV;
return 0;
}
/*
* Store information about the video data format. The color matrix
* is deeply tied into the format, so keep the relevant values here.
* The magic matrix nubmers come from OmniVision.
*/
static struct ov7670_format_struct {
__u8 *desc;
__u32 pixelformat;
struct regval_list *regs;
int cmatrix[CMATRIX_LEN];
int bpp; /* Bytes per pixel */
} ov7670_formats[] = {
{
.desc = "YUYV 4:2:2",
.pixelformat = V4L2_PIX_FMT_YUYV,
.regs = ov7670_fmt_yuv422,
.cmatrix = { 128, -128, 0, -34, -94, 128 },
.bpp = 2,
},
{
.desc = "RGB 444",
.pixelformat = V4L2_PIX_FMT_RGB444,
.regs = ov7670_fmt_rgb444,
.cmatrix = { 179, -179, 0, -61, -176, 228 },
.bpp = 2,
},
{
.desc = "RGB 565",
.pixelformat = V4L2_PIX_FMT_RGB565,
.regs = ov7670_fmt_rgb565,
.cmatrix = { 179, -179, 0, -61, -176, 228 },
.bpp = 2,
},
{
.desc = "Raw RGB Bayer",
.pixelformat = V4L2_PIX_FMT_SBGGR8,
.regs = ov7670_fmt_raw,
.cmatrix = { 0, 0, 0, 0, 0, 0 },
.bpp = 1
},
};
#define N_OV7670_FMTS ARRAY_SIZE(ov7670_formats)
/*
* Then there is the issue of window sizes. Try to capture the info here.
*/
/*
* QCIF mode is done (by OV) in a very strange way - it actually looks like
* VGA with weird scaling options - they do *not* use the canned QCIF mode
* which is allegedly provided by the sensor. So here's the weird register
* settings.
*/
static struct regval_list ov7670_qcif_regs[] = {
{ REG_COM3, COM3_SCALEEN|COM3_DCWEN },
{ REG_COM3, COM3_DCWEN },
{ REG_COM14, COM14_DCWEN | 0x01},
{ 0x73, 0xf1 },
{ 0xa2, 0x52 },
{ 0x7b, 0x1c },
{ 0x7c, 0x28 },
{ 0x7d, 0x3c },
{ 0x7f, 0x69 },
{ REG_COM9, 0x38 },
{ 0xa1, 0x0b },
{ 0x74, 0x19 },
{ 0x9a, 0x80 },
{ 0x43, 0x14 },
{ REG_COM13, 0xc0 },
{ 0xff, 0xff },
};
static struct ov7670_win_size {
int width;
int height;
unsigned char com7_bit;
int hstart; /* Start/stop values for the camera. Note */
int hstop; /* that they do not always make complete */
int vstart; /* sense to humans, but evidently the sensor */
int vstop; /* will do the right thing... */
struct regval_list *regs; /* Regs to tweak */
/* h/vref stuff */
} ov7670_win_sizes[] = {
/* VGA */
{
.width = VGA_WIDTH,
.height = VGA_HEIGHT,
.com7_bit = COM7_FMT_VGA,
.hstart = 158, /* These values from */
.hstop = 14, /* Omnivision */
.vstart = 10,
.vstop = 490,
.regs = NULL,
},
/* CIF */
{
.width = CIF_WIDTH,
.height = CIF_HEIGHT,
.com7_bit = COM7_FMT_CIF,
.hstart = 170, /* Empirically determined */
.hstop = 90,
.vstart = 14,
.vstop = 494,
.regs = NULL,
},
/* QVGA */
{
.width = QVGA_WIDTH,
.height = QVGA_HEIGHT,
.com7_bit = COM7_FMT_QVGA,
.hstart = 164, /* Empirically determined */
.hstop = 20,
.vstart = 14,
.vstop = 494,
.regs = NULL,
},
/* QCIF */
{
.width = QCIF_WIDTH,
.height = QCIF_HEIGHT,
.com7_bit = COM7_FMT_VGA, /* see comment above */
.hstart = 456, /* Empirically determined */
.hstop = 24,
.vstart = 14,
.vstop = 494,
.regs = ov7670_qcif_regs,
},
};
#define N_WIN_SIZES (ARRAY_SIZE(ov7670_win_sizes))
/*
* Store a set of start/stop values into the camera.
*/
static int ov7670_set_hw(struct i2c_client *client, int hstart, int hstop,
int vstart, int vstop)
{
int ret;
unsigned char v;
/*
* Horizontal: 11 bits, top 8 live in hstart and hstop. Bottom 3 of
* hstart are in href[2:0], bottom 3 of hstop in href[5:3]. There is
* a mystery "edge offset" value in the top two bits of href.
*/
ret = ov7670_write(client, REG_HSTART, (hstart >> 3) & 0xff);
ret += ov7670_write(client, REG_HSTOP, (hstop >> 3) & 0xff);
ret += ov7670_read(client, REG_HREF, &v);
v = (v & 0xc0) | ((hstop & 0x7) << 3) | (hstart & 0x7);
msleep(10);
ret += ov7670_write(client, REG_HREF, v);
/*
* Vertical: similar arrangement, but only 10 bits.
*/
ret += ov7670_write(client, REG_VSTART, (vstart >> 2) & 0xff);
ret += ov7670_write(client, REG_VSTOP, (vstop >> 2) & 0xff);
ret += ov7670_read(client, REG_VREF, &v);
v = (v & 0xf0) | ((vstop & 0x3) << 2) | (vstart & 0x3);
msleep(10);
ret += ov7670_write(client, REG_VREF, v);
return ret;
}
static int ov7670_enum_fmt(struct i2c_client *c, struct v4l2_fmtdesc *fmt)
{
struct ov7670_format_struct *ofmt;
if (fmt->index >= N_OV7670_FMTS)
return -EINVAL;
ofmt = ov7670_formats + fmt->index;
fmt->flags = 0;
strcpy(fmt->description, ofmt->desc);
fmt->pixelformat = ofmt->pixelformat;
return 0;
}
static int ov7670_try_fmt(struct i2c_client *c, struct v4l2_format *fmt,
struct ov7670_format_struct **ret_fmt,
struct ov7670_win_size **ret_wsize)
{
int index;
struct ov7670_win_size *wsize;
struct v4l2_pix_format *pix = &fmt->fmt.pix;
for (index = 0; index < N_OV7670_FMTS; index++)
if (ov7670_formats[index].pixelformat == pix->pixelformat)
break;
if (index >= N_OV7670_FMTS) {
/* default to first format */
index = 0;
pix->pixelformat = ov7670_formats[0].pixelformat;
}
if (ret_fmt != NULL)
*ret_fmt = ov7670_formats + index;
/*
* Fields: the OV devices claim to be progressive.
*/
pix->field = V4L2_FIELD_NONE;
/*
* Round requested image size down to the nearest
* we support, but not below the smallest.
*/
for (wsize = ov7670_win_sizes; wsize < ov7670_win_sizes + N_WIN_SIZES;
wsize++)
if (pix->width >= wsize->width && pix->height >= wsize->height)
break;
if (wsize >= ov7670_win_sizes + N_WIN_SIZES)
wsize--; /* Take the smallest one */
if (ret_wsize != NULL)
*ret_wsize = wsize;
/*
* Note the size we'll actually handle.
*/
pix->width = wsize->width;
pix->height = wsize->height;
pix->bytesperline = pix->width*ov7670_formats[index].bpp;
pix->sizeimage = pix->height*pix->bytesperline;
return 0;
}
/*
* Set a format.
*/
static int ov7670_s_fmt(struct i2c_client *c, struct v4l2_format *fmt)
{
int ret;
struct ov7670_format_struct *ovfmt;
struct ov7670_win_size *wsize;
struct ov7670_info *info = i2c_get_clientdata(c);
unsigned char com7, clkrc;
ret = ov7670_try_fmt(c, fmt, &ovfmt, &wsize);
if (ret)
return ret;
/*
* HACK: if we're running rgb565 we need to grab then rewrite
* CLKRC. If we're *not*, however, then rewriting clkrc hoses
* the colors.
*/
if (fmt->fmt.pix.pixelformat == V4L2_PIX_FMT_RGB565) {
ret = ov7670_read(c, REG_CLKRC, &clkrc);
if (ret)
return ret;
}
/*
* COM7 is a pain in the ass, it doesn't like to be read then
* quickly written afterward. But we have everything we need
* to set it absolutely here, as long as the format-specific
* register sets list it first.
*/
com7 = ovfmt->regs[0].value;
com7 |= wsize->com7_bit;
ov7670_write(c, REG_COM7, com7);
/*
* Now write the rest of the array. Also store start/stops
*/
ov7670_write_array(c, ovfmt->regs + 1);
ov7670_set_hw(c, wsize->hstart, wsize->hstop, wsize->vstart,
wsize->vstop);
ret = 0;
if (wsize->regs)
ret = ov7670_write_array(c, wsize->regs);
info->fmt = ovfmt;
if (fmt->fmt.pix.pixelformat == V4L2_PIX_FMT_RGB565 && ret == 0)
ret = ov7670_write(c, REG_CLKRC, clkrc);
return ret;
}
/*
* Implement G/S_PARM. There is a "high quality" mode we could try
* to do someday; for now, we just do the frame rate tweak.
*/
static int ov7670_g_parm(struct i2c_client *c, struct v4l2_streamparm *parms)
{
struct v4l2_captureparm *cp = &parms->parm.capture;
unsigned char clkrc;
int ret;
if (parms->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
ret = ov7670_read(c, REG_CLKRC, &clkrc);
if (ret < 0)
return ret;
memset(cp, 0, sizeof(struct v4l2_captureparm));
cp->capability = V4L2_CAP_TIMEPERFRAME;
cp->timeperframe.numerator = 1;
cp->timeperframe.denominator = OV7670_FRAME_RATE;
if ((clkrc & CLK_EXT) == 0 && (clkrc & CLK_SCALE) > 1)
cp->timeperframe.denominator /= (clkrc & CLK_SCALE);
return 0;
}
static int ov7670_s_parm(struct i2c_client *c, struct v4l2_streamparm *parms)
{
struct v4l2_captureparm *cp = &parms->parm.capture;
struct v4l2_fract *tpf = &cp->timeperframe;
unsigned char clkrc;
int ret, div;
if (parms->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
if (cp->extendedmode != 0)
return -EINVAL;
/*
* CLKRC has a reserved bit, so let's preserve it.
*/
ret = ov7670_read(c, REG_CLKRC, &clkrc);
if (ret < 0)
return ret;
if (tpf->numerator == 0 || tpf->denominator == 0)
div = 1; /* Reset to full rate */
else
div = (tpf->numerator*OV7670_FRAME_RATE)/tpf->denominator;
if (div == 0)
div = 1;
else if (div > CLK_SCALE)
div = CLK_SCALE;
clkrc = (clkrc & 0x80) | div;
tpf->numerator = 1;
tpf->denominator = OV7670_FRAME_RATE/div;
return ov7670_write(c, REG_CLKRC, clkrc);
}
/*
* Code for dealing with controls.
*/
static int ov7670_store_cmatrix(struct i2c_client *client,
int matrix[CMATRIX_LEN])
{
int i, ret;
unsigned char signbits = 0;
/*
* Weird crap seems to exist in the upper part of
* the sign bits register, so let's preserve it.
*/
ret = ov7670_read(client, REG_CMATRIX_SIGN, &signbits);
signbits &= 0xc0;
for (i = 0; i < CMATRIX_LEN; i++) {
unsigned char raw;
if (matrix[i] < 0) {
signbits |= (1 << i);
if (matrix[i] < -255)
raw = 0xff;
else
raw = (-1 * matrix[i]) & 0xff;
}
else {
if (matrix[i] > 255)
raw = 0xff;
else
raw = matrix[i] & 0xff;
}
ret += ov7670_write(client, REG_CMATRIX_BASE + i, raw);
}
ret += ov7670_write(client, REG_CMATRIX_SIGN, signbits);
return ret;
}
/*
* Hue also requires messing with the color matrix. It also requires
* trig functions, which tend not to be well supported in the kernel.
* So here is a simple table of sine values, 0-90 degrees, in steps
* of five degrees. Values are multiplied by 1000.
*
* The following naive approximate trig functions require an argument
* carefully limited to -180 <= theta <= 180.
*/
#define SIN_STEP 5
static const int ov7670_sin_table[] = {
0, 87, 173, 258, 342, 422,
499, 573, 642, 707, 766, 819,
866, 906, 939, 965, 984, 996,
1000
};
static int ov7670_sine(int theta)
{
int chs = 1;
int sine;
if (theta < 0) {
theta = -theta;
chs = -1;
}
if (theta <= 90)
sine = ov7670_sin_table[theta/SIN_STEP];
else {
theta -= 90;
sine = 1000 - ov7670_sin_table[theta/SIN_STEP];
}
return sine*chs;
}
static int ov7670_cosine(int theta)
{
theta = 90 - theta;
if (theta > 180)
theta -= 360;
else if (theta < -180)
theta += 360;
return ov7670_sine(theta);
}
static void ov7670_calc_cmatrix(struct ov7670_info *info,
int matrix[CMATRIX_LEN])
{
int i;
/*
* Apply the current saturation setting first.
*/
for (i = 0; i < CMATRIX_LEN; i++)
matrix[i] = (info->fmt->cmatrix[i]*info->sat) >> 7;
/*
* Then, if need be, rotate the hue value.
*/
if (info->hue != 0) {
int sinth, costh, tmpmatrix[CMATRIX_LEN];
memcpy(tmpmatrix, matrix, CMATRIX_LEN*sizeof(int));
sinth = ov7670_sine(info->hue);
costh = ov7670_cosine(info->hue);
matrix[0] = (matrix[3]*sinth + matrix[0]*costh)/1000;
matrix[1] = (matrix[4]*sinth + matrix[1]*costh)/1000;
matrix[2] = (matrix[5]*sinth + matrix[2]*costh)/1000;
matrix[3] = (matrix[3]*costh - matrix[0]*sinth)/1000;
matrix[4] = (matrix[4]*costh - matrix[1]*sinth)/1000;
matrix[5] = (matrix[5]*costh - matrix[2]*sinth)/1000;
}
}
static int ov7670_t_sat(struct i2c_client *client, int value)
{
struct ov7670_info *info = i2c_get_clientdata(client);
int matrix[CMATRIX_LEN];
int ret;
info->sat = value;
ov7670_calc_cmatrix(info, matrix);
ret = ov7670_store_cmatrix(client, matrix);
return ret;
}
static int ov7670_q_sat(struct i2c_client *client, __s32 *value)
{
struct ov7670_info *info = i2c_get_clientdata(client);
*value = info->sat;
return 0;
}
static int ov7670_t_hue(struct i2c_client *client, int value)
{
struct ov7670_info *info = i2c_get_clientdata(client);
int matrix[CMATRIX_LEN];
int ret;
if (value < -180 || value > 180)
return -EINVAL;
info->hue = value;
ov7670_calc_cmatrix(info, matrix);
ret = ov7670_store_cmatrix(client, matrix);
return ret;
}
static int ov7670_q_hue(struct i2c_client *client, __s32 *value)
{
struct ov7670_info *info = i2c_get_clientdata(client);
*value = info->hue;
return 0;
}
/*
* Some weird registers seem to store values in a sign/magnitude format!
*/
static unsigned char ov7670_sm_to_abs(unsigned char v)
{
if ((v & 0x80) == 0)
return v + 128;
else
return 128 - (v & 0x7f);
}
static unsigned char ov7670_abs_to_sm(unsigned char v)
{
if (v > 127)
return v & 0x7f;
else
return (128 - v) | 0x80;
}
static int ov7670_t_brightness(struct i2c_client *client, int value)
{
unsigned char com8 = 0, v;
int ret;
ov7670_read(client, REG_COM8, &com8);
com8 &= ~COM8_AEC;
ov7670_write(client, REG_COM8, com8);
v = ov7670_abs_to_sm(value);
ret = ov7670_write(client, REG_BRIGHT, v);
return ret;
}
static int ov7670_q_brightness(struct i2c_client *client, __s32 *value)
{
unsigned char v = 0;
int ret = ov7670_read(client, REG_BRIGHT, &v);
*value = ov7670_sm_to_abs(v);
return ret;
}
static int ov7670_t_contrast(struct i2c_client *client, int value)
{
return ov7670_write(client, REG_CONTRAS, (unsigned char) value);
}
static int ov7670_q_contrast(struct i2c_client *client, __s32 *value)
{
unsigned char v = 0;
int ret = ov7670_read(client, REG_CONTRAS, &v);
*value = v;
return ret;
}
static int ov7670_q_hflip(struct i2c_client *client, __s32 *value)
{
int ret;
unsigned char v = 0;
ret = ov7670_read(client, REG_MVFP, &v);
*value = (v & MVFP_MIRROR) == MVFP_MIRROR;
return ret;
}
static int ov7670_t_hflip(struct i2c_client *client, int value)
{
unsigned char v = 0;
int ret;
ret = ov7670_read(client, REG_MVFP, &v);
if (value)
v |= MVFP_MIRROR;
else
v &= ~MVFP_MIRROR;
msleep(10); /* FIXME */
ret += ov7670_write(client, REG_MVFP, v);
return ret;
}
static int ov7670_q_vflip(struct i2c_client *client, __s32 *value)
{
int ret;
unsigned char v = 0;
ret = ov7670_read(client, REG_MVFP, &v);
*value = (v & MVFP_FLIP) == MVFP_FLIP;
return ret;
}
static int ov7670_t_vflip(struct i2c_client *client, int value)
{
unsigned char v = 0;
int ret;
ret = ov7670_read(client, REG_MVFP, &v);
if (value)
v |= MVFP_FLIP;
else
v &= ~MVFP_FLIP;
msleep(10); /* FIXME */
ret += ov7670_write(client, REG_MVFP, v);
return ret;
}
static struct ov7670_control {
struct v4l2_queryctrl qc;
int (*query)(struct i2c_client *c, __s32 *value);
int (*tweak)(struct i2c_client *c, int value);
} ov7670_controls[] =
{
{
.qc = {
.id = V4L2_CID_BRIGHTNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Brightness",
.minimum = 0,
.maximum = 255,
.step = 1,
.default_value = 0x80,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.tweak = ov7670_t_brightness,
.query = ov7670_q_brightness,
},
{
.qc = {
.id = V4L2_CID_CONTRAST,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Contrast",
.minimum = 0,
.maximum = 127,
.step = 1,
.default_value = 0x40, /* XXX ov7670 spec */
.flags = V4L2_CTRL_FLAG_SLIDER
},
.tweak = ov7670_t_contrast,
.query = ov7670_q_contrast,
},
{
.qc = {
.id = V4L2_CID_SATURATION,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Saturation",
.minimum = 0,
.maximum = 256,
.step = 1,
.default_value = 0x80,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.tweak = ov7670_t_sat,
.query = ov7670_q_sat,
},
{
.qc = {
.id = V4L2_CID_HUE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "HUE",
.minimum = -180,
.maximum = 180,
.step = 5,
.default_value = 0,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.tweak = ov7670_t_hue,
.query = ov7670_q_hue,
},
{
.qc = {
.id = V4L2_CID_VFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Vertical flip",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0,
},
.tweak = ov7670_t_vflip,
.query = ov7670_q_vflip,
},
{
.qc = {
.id = V4L2_CID_HFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Horizontal mirror",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0,
},
.tweak = ov7670_t_hflip,
.query = ov7670_q_hflip,
},
};
#define N_CONTROLS (ARRAY_SIZE(ov7670_controls))
static struct ov7670_control *ov7670_find_control(__u32 id)
{
int i;
for (i = 0; i < N_CONTROLS; i++)
if (ov7670_controls[i].qc.id == id)
return ov7670_controls + i;
return NULL;
}
static int ov7670_queryctrl(struct i2c_client *client,
struct v4l2_queryctrl *qc)
{
struct ov7670_control *ctrl = ov7670_find_control(qc->id);
if (ctrl == NULL)
return -EINVAL;
*qc = ctrl->qc;
return 0;
}
static int ov7670_g_ctrl(struct i2c_client *client, struct v4l2_control *ctrl)
{
struct ov7670_control *octrl = ov7670_find_control(ctrl->id);
int ret;
if (octrl == NULL)
return -EINVAL;
ret = octrl->query(client, &ctrl->value);
if (ret >= 0)
return 0;
return ret;
}
static int ov7670_s_ctrl(struct i2c_client *client, struct v4l2_control *ctrl)
{
struct ov7670_control *octrl = ov7670_find_control(ctrl->id);
int ret;
if (octrl == NULL)
return -EINVAL;
ret = octrl->tweak(client, ctrl->value);
if (ret >= 0)
return 0;
return ret;
}
/*
* Basic i2c stuff.
*/
static struct i2c_driver ov7670_driver;
static int ov7670_attach(struct i2c_adapter *adapter)
{
int ret;
struct i2c_client *client;
struct ov7670_info *info;
/*
* For now: only deal with adapters we recognize.
*/
if (adapter->id != I2C_HW_SMBUS_CAFE)
return -ENODEV;
client = kzalloc(sizeof (struct i2c_client), GFP_KERNEL);
if (! client)
return -ENOMEM;
client->adapter = adapter;
client->addr = OV7670_I2C_ADDR;
client->driver = &ov7670_driver,
strcpy(client->name, "OV7670");
/*
* Set up our info structure.
*/
info = kzalloc(sizeof (struct ov7670_info), GFP_KERNEL);
if (! info) {
ret = -ENOMEM;
goto out_free;
}
info->fmt = &ov7670_formats[0];
info->sat = 128; /* Review this */
i2c_set_clientdata(client, info);
/*
* Make sure it's an ov7670
*/
ret = ov7670_detect(client);
if (ret)
goto out_free_info;
ret = i2c_attach_client(client);
if (ret)
goto out_free_info;
return 0;
out_free_info:
kfree(info);
out_free:
kfree(client);
return ret;
}
static int ov7670_detach(struct i2c_client *client)
{
i2c_detach_client(client);
kfree(i2c_get_clientdata(client));
kfree(client);
return 0;
}
static int ov7670_command(struct i2c_client *client, unsigned int cmd,
void *arg)
{
switch (cmd) {
case VIDIOC_G_CHIP_IDENT:
return v4l2_chip_ident_i2c_client(client, arg, V4L2_IDENT_OV7670, 0);
case VIDIOC_INT_RESET:
ov7670_reset(client);
return 0;
case VIDIOC_INT_INIT:
return ov7670_init(client);
case VIDIOC_ENUM_FMT:
return ov7670_enum_fmt(client, (struct v4l2_fmtdesc *) arg);
case VIDIOC_TRY_FMT:
return ov7670_try_fmt(client, (struct v4l2_format *) arg, NULL, NULL);
case VIDIOC_S_FMT:
return ov7670_s_fmt(client, (struct v4l2_format *) arg);
case VIDIOC_QUERYCTRL:
return ov7670_queryctrl(client, (struct v4l2_queryctrl *) arg);
case VIDIOC_S_CTRL:
return ov7670_s_ctrl(client, (struct v4l2_control *) arg);
case VIDIOC_G_CTRL:
return ov7670_g_ctrl(client, (struct v4l2_control *) arg);
case VIDIOC_S_PARM:
return ov7670_s_parm(client, (struct v4l2_streamparm *) arg);
case VIDIOC_G_PARM:
return ov7670_g_parm(client, (struct v4l2_streamparm *) arg);
}
return -EINVAL;
}
static struct i2c_driver ov7670_driver = {
.driver = {
.name = "ov7670",
},
.id = I2C_DRIVERID_OV7670,
.class = I2C_CLASS_CAM_DIGITAL,
.attach_adapter = ov7670_attach,
.detach_client = ov7670_detach,
.command = ov7670_command,
};
/*
* Module initialization
*/
static int __init ov7670_mod_init(void)
{
printk(KERN_NOTICE "OmniVision ov7670 sensor driver, at your service\n");
return i2c_add_driver(&ov7670_driver);
}
static void __exit ov7670_mod_exit(void)
{
i2c_del_driver(&ov7670_driver);
}
module_init(ov7670_mod_init);
module_exit(ov7670_mod_exit);
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/compression/lz77/lz77_comp.c | /**************************************************************************
*
* lz77_comp.c
*
* The LZ77 compression algorithm.
*
* This file is licensed under the GNU GPL.
*
* (C) 2005, <NAME> <<EMAIL>>
*
*/
#include "../compressor.h"
#include "../buffer.h"
#include "lz77.h"
#ifdef HAVE_ASSERT
# include <assert.h>
#else
# define assert(x)
#endif
#include <string.h>
uint8_t window[WINDOW_SIZE] __attribute((xdata));
uint8_t *search_start = window ;
uint8_t *search_end = window ; /* Doubles as look_ahead_start */
uint8_t *look_ahead_end = window;
uint16_t cyclic_difference(uint8_t *start, uint8_t *end)
{
if (start > end) {
end += WINDOW_SIZE;
}
return end - start;
}
uint8_t *cyclic_adjust(uint8_t *v)
{
if (v < window) {
v += WINDOW_SIZE;
} else if (v >= window + WINDOW_SIZE) {
v -= WINDOW_SIZE;
}
assert(v < window + WINDOW_SIZE && v >= window);
return v;
}
uint8_t find_match_length(uint8_t *search_pos)
{
uint8_t res = 0;
uint8_t *cur_search_pos = search_pos;
uint8_t *cur_look_ahead = search_end;
while (cur_search_pos == search_pos) {
/* Iterate for as long as we haven't reached the end of neither the
search buffer nor the look-ahead buffer, and as long as the two
buffers match */
while (cur_search_pos != search_end
&& cur_look_ahead != look_ahead_end
&& *cur_search_pos == *cur_look_ahead
&& res < LOOK_AHEAD_SIZE) {
cur_look_ahead = cyclic_adjust(cur_look_ahead + 1);
cur_search_pos = cyclic_adjust(cur_search_pos + 1);
res++;
}
if (cur_search_pos == search_end && res < LOOK_AHEAD_SIZE
&& cur_look_ahead != look_ahead_end) {
// fprintf(stderr, "Going for another round\n");
cur_search_pos = search_pos;
} else {
break;
}
}
if (res == 0) {
/* Something's fishy */
#ifdef DEBUG
fprintf(stderr, "find_match_length returns 0!?!\n");
#endif
}
assert(res <= LOOK_AHEAD_SIZE);
return res;
}
#ifdef DEBUG
void output_match(uint16_t match_offset, uint8_t len)
{
uint8_t *pos = cyclic_adjust(search_end - match_offset);
int i;
for (i = 0; i < len; i++) {
fprintf(stderr, "%02x", *pos);
pos = cyclic_adjust(pos + 1);
}
}
#endif
/*
* do_compress will compress at least a single byte.
*/
void do_compress()
{
/* Search the search buffer for the first character of the
look-ahead buffer */
uint8_t *cur_search = search_start;
uint8_t match_length = 0;
uint16_t match_offset = 0; /* The offset is the number of bytes
backwards from search_end we must go
to find the match */
while (cur_search != search_end) {
if (*cur_search == *search_end) {
/* If the first symbol in the look-ahead buffer matches our
current search character, calculate the length */
uint8_t tmp_length = find_match_length(cur_search);
if (tmp_length > match_length) {
/* If we have found a match with a greater length than the
previous match, update our match */
match_length = tmp_length;
match_offset = cyclic_difference(cur_search, search_end);
}
}
cur_search = cyclic_adjust(cur_search + 1);
}
if (match_length <= 1) {
/* If we didn't find a match, we just output the original
value. Also if we found a match and the length was only 1 byte,
the original value actually takes up less space than the
offset/length token. If the length is 2 we will use 18 bits exactly 1
bit ;-) */
write_bits(1, 1); /* This is a real value */
write_bits(*search_end, 8);
#ifdef DEBUG
fprintf(stderr, "Outputting single byte %d\n", *search_end);
#endif
/* Set the match_length to 1, so that when we move the window
later on, we will move the current item to the search buffer */
match_length = 1;
} else {
/* We did find a match. Now write a token */
write_bits(0, 1); /* This is a token */
#ifdef DEBUG
fprintf(stderr, "Outputting offset %d and length %d. Values: ",
match_offset, match_length);
output_match(match_offset, match_length);
fprintf(stderr, "\n");
#endif
/* Write the offset */
write_bits(match_offset >> 8, OFFSET_BITS - 8);
write_bits(match_offset & 0xFF, 8);
/* Write the length */
write_bits((match_length - 1) & ((1 << LENGTH_BITS) - 1), LENGTH_BITS);
}
/* Now we need to update the window */
{
uint16_t tmp_diff;
search_end = cyclic_adjust(search_end + match_length);
tmp_diff = cyclic_difference(search_start, search_end);
if (tmp_diff >= WINDOW_SIZE - LOOK_AHEAD_SIZE) {
/* We only update the start pointer if we have filled the buffer */
search_start = cyclic_adjust(search_start + tmp_diff
- WINDOW_SIZE + LOOK_AHEAD_SIZE);
}
}
/* Check if there is room enough for a nother token */
if (bits_left() < OFFSET_BITS + LENGTH_BITS + 1) {
handle_full_buffer(get_buffer(), bits_left()/(uint8_t)8);
reset_buffer();
}
}
void add_byte(uint8_t b)
{
/* Put the byte a the end of the look ahead buffer */
assert(look_ahead_end < window + WINDOW_SIZE && look_ahead_end >= window);
*look_ahead_end = b;
look_ahead_end = cyclic_adjust(look_ahead_end + 1);
/* Adjust the search_start if necessary. This happens when our
window is filled. */
if (search_start == look_ahead_end) {
search_start = cyclic_adjust(search_start + 1);
}
#ifdef DEBUG
if (bits_left() < 17) {
fprintf(stderr, "We are here, and we have less than 17 bits left?\n");
}
#endif
/* Now we should have a window with as much data as possible */
/* Check if we have our look-ahead buffer filled */
if (cyclic_difference(search_end, look_ahead_end) == LOOK_AHEAD_SIZE)
do_compress();
}
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)
{
#ifdef DIFFERENCE
static int16_t last_vals[3];
#endif
if (first) {
reset_buffer();
first = 0;
#ifdef DIFFERENCE
add_byte((digi_x >> 8) & 0xFF);
add_byte(digi_x & 0xFF);
add_byte((digi_y >> 8) & 0xFF);
add_byte(digi_y & 0xFF);
add_byte((digi_z >> 8) & 0xFF);
add_byte(digi_z & 0xFF);
last_vals[0] = digi_x;
last_vals[1] = digi_y;
last_vals[2] = digi_z;
return;
#endif
}
#ifndef DIFFERENCE
add_byte((digi_x >> 8) & 0xFF);
add_byte(digi_x & 0xFF);
add_byte((digi_y >> 8) & 0xFF);
add_byte(digi_y & 0xFF);
add_byte((digi_z >> 8) & 0xFF);
add_byte(digi_z & 0xFF);
#else
{
int16_t vals[3];
int i;
vals[0] = digi_x - last_vals[0];
vals[1] = digi_y - last_vals[1];
vals[2] = digi_z - last_vals[2];
for (i = 0; i < 3; i++) {
add_byte((vals[i] >> 8) & 0xFF);
add_byte(vals[i] & 0xFF);
}
}
last_vals[0] = digi_x;
last_vals[1] = digi_y;
last_vals[2] = digi_z;
#endif
}
void flush()
{
/* Ok. Now we need to empty our look-ahead buffer */
while (search_end != look_ahead_end) {
do_compress();
}
/* Empty the last buffer in the system */
handle_full_buffer(get_buffer(), MEMBUFSIZE - bits_left()/(uint8_t)8);
search_start = window;
search_end = window;
look_ahead_end = window;
first = 1;
}
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/util/collect/sf_lo_radio.c | #include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdint.h>
//#include <curses.h>
#include <ctype.h>
#include <limits.h>
#include <string.h>
#include <poll.h>
#include <sys/types.h>
#include "sfsource.h"
#include <time.h>
#ifndef TOSH_DATA_LENGTH
#define TOSH_DATA_LENGTH 29
#define BUNDLE_ACK_DATA_LENGTH TOSH_DATA_LENGTH-2
#endif
#ifndef _REENTRANT
#define _REENTRANT
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
//#define TRUE (! FALSE)
#define TRUE -1
#endif
#define SRC_ADDR 1
#define AM_BEGIN_TRAVERSAL_MSG 17
#define AM_GO_NEXT_MSG 18
#define AM_GET_NEXT_CHUNK 19
#define AM_GET_BUNDLE_MSG 20
#define AM_DELETE_BUNDLE_MSG 21
#define AM_DELETE_ALL_BUNDLES_MSG 22
#define AM_END_DATA_COLLECTION_SESSION 23
#define AM_BUNDLE_INDEX_ACK 24
#define AM_RADIO_HI_POWER 25
#define AM_RADIO_LO_POWER 26
#define AM_DEADLOCK_MSG 27
#define AM_DELETE_ALL_ACK 28
#define MAX_RETRYS 10
#define MSG_HEADER_OFFSET 5
#define MSG_DATA_OFFSET 9
#define MSG_STATUS_OFFSET 7
///////////////////////////////////////////////////////////////////////////////////////////////////
// TYPEDEFS
///////////////////////////////////////////////////////////////////////////////////////////////////
typedef struct TOS_Msg
{
uint16_t addr;
uint8_t type;
uint8_t group;
uint8_t length;
int8_t data[TOSH_DATA_LENGTH];
uint16_t crc;
} TOS_Msg;
typedef uint8_t bool;
///////////////////////////////////////////////////////////////////////////////////////////////////
// TINYOS COMM STRUCTS
///////////////////////////////////////////////////////////////////////////////////////////////////
typedef struct BeginTraversalMsg {
uint16_t src_addr;
uint8_t seq_num;
} BeginTraversalMsg_t;
typedef struct GoNextMsg {
uint16_t src_addr;
uint8_t seq_num;
} GoNextMsg_t;
typedef struct GetBundleMsg {
uint16_t src_addr;
uint8_t seq_num;
} GetBundleMsg_t;
typedef struct DeleteBundleMsg {
uint16_t src_addr;
uint8_t seq_num;
} DeleteBundleMsg_t;
typedef struct BundleIndexAck {
uint16_t src_addr;
bool success;
uint8_t seq_num;
char data[BUNDLE_ACK_DATA_LENGTH];
} BundleIndexAck_t;
typedef struct GetNextChunk{
uint16_t src_addr;
uint8_t seq_num;
} GetNextChunk_t;
typedef struct EndCollectionSession{
uint16_t src_addr;
uint8_t seq_num;
} EndCollectionSession_t;
///////////////////////////////////////////////////////////////////////////////////////////////////
// WRAPPERS
///////////////////////////////////////////////////////////////////////////////////////////////////
typedef struct w_BT {
uint16_t addr;
uint8_t type;
uint8_t group;
uint8_t length;
uint16_t src_addr;
uint8_t seq_num;
} w_BT_t;
typedef struct w_GN {
uint16_t addr;
uint8_t type;
uint8_t group;
uint8_t length;
uint16_t src_addr;
uint8_t seq_num;
} w_GN_t;
typedef struct w_GB {
uint16_t addr;
uint8_t type;
uint8_t group;
uint8_t length;
uint16_t src_addr;
uint8_t seq_num;
} w_GB_t;
typedef struct w_DB {
uint16_t addr;
uint8_t type;
uint8_t group;
uint8_t length;
uint16_t src_addr;
uint8_t seq_num;
} w_DB_t;
typedef struct w_GNC {
uint16_t addr;
uint8_t type;
uint8_t group;
uint8_t length;
uint16_t src_addr;
uint8_t seq_num;
} w_GNC_t;
typedef struct w_ECS {
uint16_t addr;
uint8_t type;
uint8_t group;
uint8_t length;
uint16_t src_addr;
uint8_t seq_num;
} w_ECS_t;
typedef struct gen_msg {
uint16_t addr;
uint8_t type;
uint8_t group;
uint8_t length;
uint16_t src_addr;
uint8_t seq_num;
} gen_msg_t;
#pragma pack(1)
typedef struct TOS_write
{
int fd;
int mote_addr;
} TOS_write_t;
#define TOS_MSG_SIZE 2*sizeof(uint16_t) + 4*sizeof(uint8_t)
#define MSG_TIMEOUT 2000
void* get_packet( gen_msg_t *tos)
{
void *ret = malloc(TOS_MSG_SIZE);
int offset = 0;
memcpy(ret+offset, &tos->addr, sizeof(uint16_t) );
offset += sizeof(uint16_t);
memcpy(ret+offset, &tos->type, sizeof(uint8_t) );
offset += sizeof(uint8_t);
memcpy(ret+offset, &tos->group, sizeof(uint8_t) );
offset += sizeof(uint8_t);
memcpy(ret+offset, &tos->length, sizeof(uint8_t) );
offset += sizeof(uint8_t);
memcpy(ret+offset, &tos->src_addr, sizeof(uint16_t) );
offset += sizeof(uint16_t);
memcpy(ret+offset, &tos->seq_num, sizeof(uint8_t) );
return ret;
}
void* mote_write(void *buf)
{
TOS_write_t *tos = (TOS_write_t *) buf;
uint8_t seq_num = 0;
gen_msg_t msg;
char *my_string;
int nbytes = 100;
int bytes_read;
msg.addr = tos->mote_addr;
msg.group = 0x7d;
msg.length = sizeof(uint16_t)+sizeof(uint8_t);
msg.src_addr = SRC_ADDR;
printf("What would you like to do: \n");
printf("bd: Bundle Delete \n");
printf("gb: Get Bundle \n");
printf("gc: Get Next Chunk \n");
printf("bt: Begin Traversal \n");
printf("gn: Go Next \n");
printf("ec: End Collection Session\n");
while (1)
{
int w_ret = 0;
void *data;
my_string = (char *) malloc (nbytes + 1);
bytes_read = getline (&my_string, &nbytes, stdin);
if (my_string[0] == 's' && my_string[1] == 'n')
{
seq_num++;
printf ("Sequence Number incremented: %d\n",seq_num);
}
if (my_string[0] == 'b' && my_string[1] == 'd')
{
msg.seq_num = seq_num;
msg.type = AM_DELETE_BUNDLE_MSG;
data = get_packet(&msg);
w_ret = write_sf_packet(tos->fd, data, TOS_MSG_SIZE);
free(data);
}
if (my_string[0] == 'g' && my_string[1] == 'b')
{
msg.seq_num = seq_num;
msg.type = AM_GET_BUNDLE_MSG;
data = get_packet(&msg);
w_ret = write_sf_packet(tos->fd, data, TOS_MSG_SIZE);
free(data);
}
if (my_string[0] == 'g' && my_string[1] == 'c')
{
msg.seq_num = seq_num;
msg.type = AM_GET_NEXT_CHUNK;
data = get_packet(&msg);
w_ret = write_sf_packet(tos->fd, data, TOS_MSG_SIZE);
free(data);
}
if (my_string[0] == 'b' && my_string[1] == 't')
{
msg.seq_num = seq_num;
msg.type = AM_BEGIN_TRAVERSAL_MSG;
data = get_packet(&msg);
w_ret = write_sf_packet(tos->fd, data, TOS_MSG_SIZE);
free(data);
}
if (my_string[0] == 'g' && my_string[1] == 'n')
{
msg.seq_num = seq_num;
msg.type = AM_GO_NEXT_MSG;
data = get_packet(&msg);
w_ret = write_sf_packet(tos->fd, data, TOS_MSG_SIZE);
free(data);
}
if (my_string[0] == 'e' && my_string[1] == 'c')
{
msg.seq_num = seq_num;
msg.type = AM_END_DATA_COLLECTION_SESSION;
data = get_packet(&msg);
w_ret = write_sf_packet(tos->fd, data, TOS_MSG_SIZE);
free(data);
}
if (w_ret == -1)
{
printf("error writing to socket... exiting\n");
exit (0);
}
}
return NULL;
}
void mote_read(void *buf)
{
TOS_write_t *tos = (TOS_write_t *) buf;
for (;;)
{
int len, i;
struct pollfd pl;
pl.fd = tos->fd;
pl.events = POLLIN;
//if (poll(&pl, 1, 3000))
if (poll(&pl, 1, 1500))
{
printf("about to read: \n");
}
else
{
printf("timed out \n");
}
const unsigned char *packet = read_sf_packet(tos->fd, &len);
if (!packet)
exit(0);
for (i = 0; i < len; i++)
{
if (i == 5 || i== 9)
printf("| ");
printf("%02x ", packet[i]);
}
putchar('\n');
fflush(stdout);
free((void *)packet);
}
}
enum
{
STATE_START_TRAVERSAL,
STATE_GET_BUNDLE,
STATE_GET_NEXT_CHUNK,
STATE_G0_NEXT_BUNDLE,
STATE_END_COLLECTION
};
bool listen_for_message(const unsigned char **packet, int fd, int *length)
{
struct pollfd pl;
int len;
pl.fd = fd;
pl.events = POLLIN;
if (poll(&pl, 1, MSG_TIMEOUT))
{
// read that packet;
*packet = read_sf_packet(fd, &len);
// we got a packet but it's not the kind we were expecting...
if ( (*packet)[2] != 23)
{
free(*packet);
*packet = NULL;
return listen_for_message(packet, fd, length);
}
else
{
//print_received_message(*packet, fd, len);
*length = len;
return TRUE;
}
}
else
{
*length = -1;
return FALSE;
}
//return packet;
}
void print_received_message(const unsigned char *packet, int len)
{
int i;
for (i = 0; i < len; i++)
{
if (i == MSG_HEADER_OFFSET || i == MSG_DATA_OFFSET)
printf("| ");
printf("%02x ", packet[i]);
}
printf("\n");
}
void print_data_message(const unsigned char *packet, int len, FILE *Fp)
{
int i;
for (i = 0; i < len; i++)
{
//if (i == MSG_HEADER_OFFSET || i == MSG_DATA_OFFSET)
// printf("| ");
fprintf(Fp, "%02x ", packet[i]);
}
fprintf(Fp, "\n");
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// This is where the Magic Happens
///////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
///////////////////////////////////////////////////////////////////////////////////////////////
// Communication Variables
///////////////////////////////////////////////////////////////////////////////////////////////
int fd;
int mote_addr;
TOS_write_t tos_write;
struct pollfd pl;
///////////////////////////////////////////////////////////////////////////////////////////////
// Collection Variables
///////////////////////////////////////////////////////////////////////////////////////////////
gen_msg_t msg;
int state = STATE_START_TRAVERSAL;
int seq_num = 0;
int num_retrys = 0;
int total_msgs;
uint32_t num_bundles = 0;
uint32_t curr_nundle_num = 0;
FILE *Fp;
///////////////////////////////////////////////////////////////////////////////////////////////
// Thread Variables
///////////////////////////////////////////////////////////////////////////////////////////////
pthread_t *read_thread;
pthread_t *write_thread;
pthread_attr_t pthread_custom_attr;
pthread_attr_init(&pthread_custom_attr);
read_thread = (pthread_t *) malloc(sizeof(pthread_t));
write_thread = (pthread_t *) malloc(sizeof(pthread_t));
if (argc != 4)
{
fprintf(stderr, "Usage: %s <host> <port> <mote_addr> - dump packets from a serial forwarder %d \n", argv[0], argc);
exit(2);
}
fd = open_sf_source(argv[1], atoi(argv[2]));
if (fd < 0)
{
fprintf(stderr, "Couldn't open serial forwarder at %s:%s\n", argv[1], argv[2]);
exit(1);
}
Fp = fopen("data.txt", "w+");
mote_addr = atoi(argv[3]);
msg.addr = mote_addr;
msg.group = 0x7d;
msg.length = sizeof(uint16_t)+sizeof(uint8_t);
msg.src_addr = SRC_ADDR;
pl.fd = fd;
pl.events = POLLIN;
while (1337)
{
void *data;
int w_ret;
msg.seq_num = seq_num++;
msg.type = AM_RADIO_LO_POWER;
data = get_packet(&msg);
w_ret = write_sf_packet(fd, data, TOS_MSG_SIZE);
usleep(256*1024);
}
/*
while (1337)
{
int w_ret;
void *data;
int len;
int i;
const unsigned char *packet;
switch (state) {
case STATE_START_TRAVERSAL:
printf ("Sending BEGIN_TRAVERSAL Message \n");
msg.seq_num = seq_num;
msg.type = AM_BEGIN_TRAVERSAL_MSG;
data = get_packet(&msg);
w_ret = write_sf_packet(fd, data, TOS_MSG_SIZE);
if ( listen_for_message(&packet, fd, &len) )
{
// we got a response, but did we succeed?
if (packet[MSG_STATUS_OFFSET] != 0x00)
{
seq_num++;
num_retrys = 0;
printf ("BeginTraversal succeeded \n");
memcpy(&num_bundles, &packet[9], sizeof(uint32_t));
printf ("There should be %d bundles \n\n" , num_bundles);
fprintf(Fp, "There should be %d bundles \n\n", num_bundles);
state = STATE_GET_BUNDLE;
}
else
{
if (num_retrys > MAX_RETRYS)
{
printf ("BeginTraversal FAILED.. EXITING \n");
exit(0);
}
num_retrys++;
seq_num++;
printf ("BeginTraversal FAILED.. trying again \n\n");
}
free (packet);
}
free(data);
break;
case STATE_GET_BUNDLE:
printf ("Sending GET_BUNDLE_MSG Message \n");
msg.seq_num = seq_num;
msg.type = AM_GET_BUNDLE_MSG;
data = get_packet(&msg);
w_ret = write_sf_packet(fd, data, TOS_MSG_SIZE);
if ( listen_for_message(&packet, fd, &len) )
{
// we got a response, but did we succeed?
if (packet[MSG_STATUS_OFFSET] == 0x01)
{
uint16_t turtle_num;
uint16_t bundle_num;
num_retrys = 0;
seq_num++;
curr_nundle_num++;
state = STATE_GET_NEXT_CHUNK;
printf ("GetBundle succeeded \n");
print_received_message(packet, len);
memcpy(&turtle_num, &packet[9], sizeof(uint16_t) );
memcpy(&bundle_num, &packet[11], sizeof(uint16_t) );
fprintf(Fp, "Turtle: %d Bundle: %d\n", turtle_num, bundle_num);
}
else if (packet[MSG_STATUS_OFFSET] == 0x02) // we got the bundle, but it's not valid
{
num_retrys = 0;
seq_num++;
state = STATE_G0_NEXT_BUNDLE;
printf ("GetBundle succeeded but the bundle is invalid \n");
}
else // BAD
{
if (num_retrys > MAX_RETRYS)
{
printf ("GetBundle FAILED.. EXITING \n");
exit(0);
}
state = STATE_GET_BUNDLE;
num_retrys++;
printf ("ERROR: GetBundle failed... trying again \n");
}
free(packet);
}
free (data);
break;
case STATE_GET_NEXT_CHUNK:
printf ("Sending GET_NEXT_CHUNK Message \n");
msg.seq_num = seq_num;
msg.type = AM_GET_NEXT_CHUNK;
data = get_packet(&msg);
w_ret = write_sf_packet(fd, data, TOS_MSG_SIZE);
if ( listen_for_message(&packet, fd, &len) )
{
if (packet[MSG_STATUS_OFFSET] == 0x01)
{
num_retrys = 0;
seq_num++;
state = STATE_GET_NEXT_CHUNK;
printf ("GetNextChunk succeeded \n");
print_data_message(packet, len, Fp);
//fprintf(Fp, "%s\n", packet);
}
else if (packet[MSG_STATUS_OFFSET] == 0x02) // we got the bundle, but it's not valid
{
num_retrys = 0;
seq_num++;
state = STATE_G0_NEXT_BUNDLE;
printf ("We reached the end of this stream \n");
fprintf(Fp, "\n");
if (curr_nundle_num == num_bundles)
{
printf ("We got all the bundles. Let's end the collection session. \n");
state = STATE_END_COLLECTION;
}
}
else // BAD
{
if (num_retrys > MAX_RETRYS)
{
printf ("GetNextChunk FAILED.. EXITING \n");
exit(0);
}
num_retrys++;
printf ("ERROR: GetNextChunk failed... trying again \n");
state = STATE_GET_NEXT_CHUNK;
}
free(packet);
}
free (data);
break;
case STATE_G0_NEXT_BUNDLE:
printf ("Sending G0_NEXT_BUNDLE Message \n");
msg.seq_num = seq_num;
msg.type = AM_GO_NEXT_MSG;
data = get_packet(&msg);
w_ret = write_sf_packet(fd, data, TOS_MSG_SIZE);
if ( listen_for_message(&packet, fd, &len) )
{
if (packet[MSG_STATUS_OFFSET] == 0x01)
{
num_retrys = 0;
seq_num++;
state = STATE_GET_BUNDLE;
printf ("GoNext succeeded \n");
}
else // BAD
{
if (num_retrys > MAX_RETRYS)
{
printf ("GoNext FAILED.. Ending Collection Session \n");
state = STATE_END_COLLECTION;
exit(0);
}
seq_num++;
num_retrys++;
printf ("ERROR: GetNextChunk failed... trying again \n");
state = STATE_G0_NEXT_BUNDLE;
}
free(packet);
}
free (data);
break;
case STATE_END_COLLECTION:
printf ("Sending G0_END_COLLECTION Message \n");
msg.seq_num = seq_num;
msg.type = AM_END_DATA_COLLECTION_SESSION;
data = get_packet(&msg);
w_ret = write_sf_packet(fd, data, TOS_MSG_SIZE);
if ( listen_for_message(&packet, fd, &len) )
{
if (packet[MSG_STATUS_OFFSET] == 0x01)
{
num_retrys = 0;
printf ("EndCollectionSession succeeded. exiting... \n");
fclose(Fp);
exit(0);
}
else
{
if (num_retrys > MAX_RETRYS)
{
printf ("EndCollectionSession FAILED.. EXITING \n");
exit(0);
}
num_retrys++;
printf ("ERROR: EndCollectionSession failed... trying again \n");
state = AM_END_DATA_COLLECTION_SESSION;
}
free(packet);
}
free (data);
break;
default:
printf("ERROR: %d is not a known state\n", state);
exit(0);
break;
}
if (w_ret == -1)
{
printf("error writing to socket... exiting\n");
exit (0);
}
}
*/
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | wustl/upma/lib/macs/ss-tdma/ss_tdma.h | <filename>wustl/upma/lib/macs/ss-tdma/ss_tdma.h
#define ZMAC_OFFSET 16 //32Hz
#define ZMAC_CHECK_INTERVAL 1 //ms
#define ZMAC_BACKOFF 16
#define ZMAC_SLOT_SIZE 10 *32 //ms |
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libnxt/main_fwflash.c | /**
* Main program code for the fwflash utility.
*
* 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 <stdlib.h>
#include "error.h"
#include "lowlevel.h"
#include "samba.h"
#include "firmware.h"
#define NXT_HANDLE_ERR(expr, nxt, msg) \
do { \
nxt_error_t nxt__err_temp = (expr); \
if (nxt__err_temp) \
return handle_error(nxt, msg, nxt__err_temp); \
} while(0)
static int handle_error(nxt_t *nxt, char *msg, nxt_error_t err)
{
printf("%s: %s\n", msg, nxt_str_error(err));
if (nxt != NULL)
nxt_close(nxt);
exit(err);
}
int main(int argc, char *argv[])
{
nxt_t *nxt;
nxt_error_t err;
char *fw_file;
if (argc != 2)
{
printf("Syntax: %s <firmware image to write>\n"
"\n"
"Example: %s nxtos.bin\n", argv[0], argv[0]);
exit(1);
}
fw_file = argv[1];
printf("Checking firmware... ");
NXT_HANDLE_ERR(nxt_firmware_validate(fw_file), NULL,
"Error");
printf("OK.\n");
NXT_HANDLE_ERR(nxt_init(&nxt), NULL,
"Error during library initialization");
err = nxt_find(nxt);
if (err)
{
if (err == NXT_NOT_PRESENT)
printf("NXT not found. Is it properly plugged in via USB?\n");
else
NXT_HANDLE_ERR(0, NULL, "Error while scanning for NXT");
exit(1);
}
if (!nxt_in_reset_mode(nxt))
{
printf("NXT found, but not running in reset mode.\n");
printf("Please reset your NXT manually and restart this program.\n");
exit(2);
}
NXT_HANDLE_ERR(nxt_open(nxt), NULL, "Error while connecting to NXT");
printf("NXT device in reset mode located and opened.\n"
"Starting firmware flash procedure now...\n");
NXT_HANDLE_ERR(nxt_firmware_flash(nxt, fw_file), nxt,
"Error flashing firmware");
printf("Firmware flash complete.\n");
NXT_HANDLE_ERR(nxt_jump(nxt, 0x00100000), nxt,
"Error booting new firmware");
printf("New firmware started!\n");
NXT_HANDLE_ERR(nxt_close(nxt), NULL,
"Error while closing connection to NXT");
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/tinyos2/fluxhandler.h | #ifndef FLUXHANDLER_H_INCLUDED
#define FLUXHANDLER_H_INCLUDED
#include "rt_structs.h"
//#include "MemAlloc.h"
bool isReadyByID (EdgeIn * edge);
error_t callEdge (EdgeIn * e);
error_t adjustIntervals();
task void FinishRecoverTask();
error_t getOutSize (EdgeIn * e);
error_t handle_error (uint16_t nodeid, uint8_t * indata, uint8_t error);
uint16_t translateIDAll (EdgeIn * e, uint16_t * wt);
void *getInVar(uint16_t nodeid);
void *getOutVar(uint16_t nodeid);
error_t callError (
uint16_t nodeid,
uint8_t * in,
uint8_t error);
uint16_t getErrorWeight (uint16_t nodeid);
//void factorSGDC (uint8_t state, bool awake);
bool islocal (uint16_t nodeid);
//bool doremoteenqueue (EdgeQueue * q, EdgeIn edge);
//task void RemoteConsumerTask ();
//task void SleepTask();
//global variables
/*enum {
ASLEEP =0,
SLEEPY =1,
AWAKE =3,
WAKING =4,
};
int remoteCstate = ASLEEP;
*/
event void RTClockTimer.fired()
{
atomic rt_clock++;
}
event void EvalTimer.fired()
{
call IEval.reeval_energy_level();
}
event void IEval.reeval_done(uint8_t state, double grade)
{
curstate = state;
curgrade = grade;
adjustIntervals();
}
/************************************
*
* EDGE Consumer/Producer functions
*
************************************/
task void
LocalConsumerTask ()
{
uint16_t result;
uint16_t delay;
EdgeIn edge;
//bool edgefailed;
delay = FALSE;
result = dequeue (&moteQ, &edge);
if (result == TRUE)
{
call PowerDisable(); //no power management in nodes
result = callEdge(&edge);
if (result == FAIL)
{
call PowerEnable();
__release_node_lock (edge.node_id);
handle_error (edge.node_id, edge.invar, ERR_NOMEMORY);
}
} //if
atomic
{
if (isqueueempty (&moteQ))
{
localCAlive = FALSE;
}
}//atomic
if (localCAlive == TRUE)
{
if (delay == TRUE)
{
//delay execution a little bit
call localQTimer.startOneShot(QUEUE_DELAY);
}
else
{
post LocalConsumerTask ();
} //else(delay)
}//else(still alive)
} //end LocalConsumerTask
event void localQTimer.fired ()
{
if (!post LocalConsumerTask ())
{
call localQTimer.startOneShot(QUEUE_DELAY);
}
}
bool check_retry()
{
save_retries++;
if (save_retries > MAX_SAVE_RET)
{
return FALSE;
} else {
return TRUE;
}
}
task void ReadStateTask()
{
if (call PageEEPROM.read(SAVE_PAGE, 0, &__rtstate, sizeof(__runtime_state_t)) != SUCCESS)
{
if (check_retry())
{
post ReadStateTask();
} else {
post FinishRecoverTask();
}
}
}
task void FinishRecoverTask()
{
int i;
int j=0;
int numpaths = 0;
//initial capacity assumption.
//if recovering from a dead spell, this will be
//detected and corrected in SrcAccumM.nc
__rtstate.batt_reserve = BATTERY_CAPACITY/2;
if (__rtstate.save_flag != 0xDEAD)
{
//no data to recover
//assign defaults
__rtstate.load_avg = 0.0;
//initialize sources and paths
for (j=0; j < NUMSOURCES; j++)
{
numpaths = 0;
for (i=0; i < NUMPATHS; i++)
{
if (read_pgm_int8((int8_t*)&pathSrc[i]) == j) numpaths++;
}
for (i=0; i < NUMPATHS; i++)
{
if (read_pgm_int8((int8_t*)&pathSrc[i]) == j)
{
__rtstate.prob[i] = (100 / numpaths);
__rtstate.pc[i] = 0;
}
}
__rtstate.srcprob[j] = 0;
__rtstate.spc[j] = 0;
}
//initialize path energy
for (i=0; i < NUMPATHS; i++)
{
__rtstate.pathenergy[i] = -1;
}
}
}
event error_t PageEEPROM.readDone(error_t res)
{
post FinishRecoverTask();
return SUCCESS;
}
/*
Runtime data recovery functions
*/
error_t recoverRunTimeData()
{
save_retries = 0;
__rtstate.save_flag = 0;
//post ReadStateTask();
post FinishRecoverTask();
return SUCCESS;
}
event void RecoverTimer.fired ()
{
recoverRunTimeData();
}
task void FlushPageTask()
{
if (call PageEEPROM.flush(SAVE_PAGE) != SUCCESS)
{
if (check_retry()) post FlushPageTask();
}
}
task void SaveTask()
{
if (call PageEEPROM.write(SAVE_PAGE, 0, &__rtstate, sizeof(__runtime_state_t)) != SUCCESS)
{
if (check_retry()) post SaveTask();
}
}
task void EraseTask()
{
if (call PageEEPROM.erase(SAVE_PAGE, TOS_EEPROM_ERASE) != SUCCESS)
{
if (check_retry()) post EraseTask();
}
}
event void SaveTimer.fired ()
{
//Save runtime data
__rtstate.save_flag = 0xDEAD;
save_retries = 0;
//post EraseTask();
}
event error_t PageEEPROM.writeDone(error_t res)
{
if (res == SUCCESS)
{
save_retries = 0;
post FlushPageTask();
}
else if (check_retry())
{
post SaveTask();
}
return (SUCCESS);
}
event error_t PageEEPROM.flushDone(error_t res)
{
//We made it! Yeah!
return (SUCCESS);
}
event error_t PageEEPROM.eraseDone(error_t res)
{
if (res == SUCCESS)
{
post SaveTask();
} else if (check_retry())
{
post EraseTask();
}
return (SUCCESS);
}
event error_t PageEEPROM.syncDone(error_t result)
{
return (SUCCESS);
}
event error_t PageEEPROM.computeCrcDone(error_t result, uint16_t crc)
{
return (SUCCESS);
}
bool
isFunctionalState (uint8_t state)
{
return (curstate <= state);
}
/*********************************
* A wrapper for enqueue to manage
* the posting of consumer tasks
********************************/
bool
dolocalenqueue (EdgeQueue * q, EdgeIn edge)
{
bool result;
queue_ptr = q;
atomic
{
result = enqueue (q, edge);
if (result && localCAlive == FALSE)
{
localCAlive = TRUE;
post LocalConsumerTask ();
}
} //atomic
return result;
}
#ifdef RUNTIME_TEST
event error_t SendMsg.sendDone(TOS_MsgPtr msg, error_t success)
{
return SUCCESS;
}
#endif
/********************************
* AUX functions
********************************/
uint16_t
getNextSession ()
{
uint16_t nextid;
atomic
{
nextid = session_id;
session_id++;
}
return nextid;
}
error_t handle_exit (uint16_t nodeid, uint8_t* data)
{
error_t res;
GenericNode *ndata = (GenericNode *) data;
__release_node_lock(nodeid);
res = call IEnergyMap.endPath(ndata->_pdata.sessionID, ndata->_pdata.weight);
return SUCCESS;
}
event void IEnergyMap.pathEnergy(uint16_t path, uint32_t energy, bool micro)
{
//report path completion
//energy is in 100 uJ <or> 0.1 mJ
call IEval.reportPathDone(path, curstate, energy);
signal IPathDone.done(path, energy, __rtstate.prob[path], __rtstate.srcprob[pathSrc[path]]);
}
event error_t DummyPathDone.done(uint16_t pathid, uint32_t cost, uint8_t prob, uint8_t srcprob)
{
return SUCCESS;
}
error_t
handle_error (uint16_t nodeid, uint8_t * indata, uint8_t error)
{
//add weight
GenericNode *ndata = (GenericNode *) indata;
ndata->_pdata.weight += getErrorWeight (nodeid);
/*if (error == ERR_NOMEMORY)
{
}
if (error == ERR_QUEUE)
{
}*/
//call the correct error handler
return callError (nodeid, indata, error);
}
//CODE FOR HANDLING EDGES BETWEEN NODES
error_t
handle_edge (uint16_t oldid, uint16_t nodeid,
uint8_t* outdata, bool local, uint16_t edgewt)
{
EdgeIn newedge, oldedge;
uint16_t wt;
uint16_t dest;
atomic {
__release_node_lock (oldid);
newedge.node_id = nodeid;
//temporarily point to this for type-checking
((GenericNode *)outdata)->_pdata.weight += edgewt;
newedge.invar = outdata;
dest = translateIDAll (&newedge, &wt);
newedge.node_id = dest;
((GenericNode *)outdata)->_pdata.weight += wt;
if (__try_node_lock (dest) == TRUE)
{
//got the lock
newedge.invar = getInVar(newedge.node_id);
newedge.outvar = getOutVar(newedge.node_id);
oldedge.node_id = oldid;
memcpy(newedge.invar, outdata, getOutSize(&oldedge));
//((GenericNode *)newedge.invar)->_pdata.weight += (edgewt + wt);
((GenericNode *)newedge.outvar)->_pdata.weight = ((GenericNode *)newedge.invar)->_pdata.weight;
((GenericNode *)newedge.outvar)->_pdata.sessionID = ((GenericNode *)newedge.invar)->_pdata.sessionID;
((GenericNode *)newedge.outvar)->_pdata.minstate = ((GenericNode *)newedge.invar)->_pdata.minstate;
if (!dolocalenqueue (&moteQ, newedge))
{
__release_node_lock (dest);
//queue is full
return handle_error (dest, newedge.invar, ERR_QUEUE);
}
} else {
return handle_error (dest, outdata, ERR_USR);
}
} //atomic
return SUCCESS;
}
//CODE FOR HANDLING EDGES FROM SOURCES TO NODES
error_t
handle_src_edge (uint16_t oldid, uint16_t nodeid,
uint8_t* outdata,
uint16_t session, bool local, uint16_t edgewt)
{
EdgeIn newedge, oldedge;
uint16_t wt;
uint16_t dest;
atomic
{
newedge.node_id = nodeid;
dest = translateIDAll (&newedge, &wt);
newedge.node_id = dest;
if (__try_node_lock(newedge.node_id) == TRUE)
{
//got the lock
newedge.invar = getInVar(newedge.node_id);
newedge.outvar = getOutVar(newedge.node_id);
oldedge.node_id = oldid;
memcpy(newedge.invar, outdata, getOutSize(&oldedge));
((GenericNode *)newedge.invar)->_pdata.sessionID = session;
((GenericNode *)newedge.invar)->_pdata.weight += (edgewt + wt);
((GenericNode *)newedge.invar)->_pdata.minstate = STATE_BASE;
//memcpy(&newedge.outvar, newedge.invar, sizeof(rt_data));
((GenericNode *)newedge.outvar)->_pdata.sessionID = session;
((GenericNode *)newedge.outvar)->_pdata.weight = ((GenericNode *)newedge.invar)->_pdata.weight;
((GenericNode *)newedge.outvar)->_pdata.minstate = ((GenericNode *)newedge.invar)->_pdata.minstate;
if (!dolocalenqueue (&moteQ, newedge))
{
__release_node_lock (dest);
//queue is full
return handle_error (dest, newedge.invar, ERR_QUEUE);
}
call IEnergyMap.startPath(session);
}
} //atomic
return SUCCESS;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/stargate/rt_marshall.h | <filename>eon/eon/src/runtime/stargate/rt_marshall.h
#ifndef _RT_MARSHALL_H_
#define _RT_MARSHALL_H_
#include "rt_structs.h"
#include "../usermarshall.h"
#define TYPE_START 0
#define TYPE_END 1
#define TYPE_UINT8 2
#define TYPE_UINT16 3
#define TYPE_UINT32 4
#define TYPE_INT8 5
#define TYPE_INT16 6
#define TYPE_INT32 7
#define MARSH_OK 0
#define MARSH_ERR 1
#define MARSH_FULL 2
#define MARSH_WAIT 3
#define MARSH_TYPE 4
int unmarshall_start(int cid, uint16_t *nodeid);
int unmarshall_end(int cid, uint16_t *nodeid);
int unmarshall_session(int cid, rt_data *_pdata);
int unmarshall_uint8_t(int cid, uint8_t *data);
int unmarshall_int8_t(int cid, int8_t *data);
int unmarshall_uint16_t(int cid, uint16_t *data);
int unmarshall_int16_t(int cid, int16_t *data);
int unmarshall_uint32_t(int cid, uint32_t *data);
int unmarshall_int32_t(int cid, int32_t *data);
int unmarshall_bool(int cid, bool *data);
int unmarshall_request_t(int cid, request_t* data);
int marshall_start(int cid, uint16_t nodeid);
int marshall_session(int cid, rt_data _pdata);
int marshall_int8_t(int cid, int8_t data);
int marshall_uint8_t(int cid, uint8_t data);
int marshall_int16_t(int cid, int16_t data);
int marshall_uint16_t(int cid, uint16_t data);
int marshall_int32_t(int cid, int32_t data);
int marshall_uint32_t(int cid, uint32_t data);
int marshall_char(int cid, char data);
int marshall_bool(int cid, bool data);
int marshall_request_t(int cid, request_t data);
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/tinyos2/energystructs.h | #ifndef ENERGYSTRUCTS_H_INCLUDED
#define ENERGYSTRUCTS_H_INCLUDED
#define _NUMBUCKETS 10
typedef struct energy_pdf_t
{
} energy_pred_t;
#endif |
tinyos-io/tinyos-3.x-contrib | vu/tos/lib/dfrf/DfrfMsg.h | /*
* Copyright (c) 2009, 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>, <NAME>
* <NAME>, <EMAIL>
* <NAME>
* Date last modified: 06/30/03
*/
#ifndef __DFRFMSG_H__
#define __DFRFMSG_H__
#include "message.h"
typedef nx_struct dfrf_msg
{
nx_uint8_t appId; // the application id, distinguishes different applications
// using FloodRouting parametrized interface
nx_uint16_t location; // see RoutingPolicy
// nx_uint32_t timeStamp;
nx_uint8_t data[0]; // actual packets, max length is FLOODROUTING_MAXDATA
} dfrf_msg_t;
enum {
AM_DFRF_MSG = 0x82,
};
#endif // __DFRFMSG_H__
|
tinyos-io/tinyos-3.x-contrib | uob/tossdr/ucla/gnuradio-802.15.4-demodulation/src/lib/ucla_multichanneladd_cc.h | /* -*- c++ -*- */
/*
* Copyright 2004 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio 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, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
/**
* This is a modification of the gr_multichanneladd_cc from GNURadio.
*
* Modified by: <NAME> <<EMAIL>>
*/
#ifndef INCLUDED_UCLA_MULTICHANNELADD_CC_H
#define INCLUDED_UCLA_MULTICHANNELADD_CC_H
#include <gr_sync_interpolator.h>
class ucla_multichanneladd_cc;
typedef boost::shared_ptr<ucla_multichanneladd_cc> ucla_multichanneladd_cc_sptr;
ucla_multichanneladd_cc_sptr ucla_make_multichanneladd_cc (size_t itemsize);
/*!
* \brief multichanneladd_cc N inputs to a single output
* \ingroup block
*/
class ucla_multichanneladd_cc : public gr_block
{
friend ucla_multichanneladd_cc_sptr ucla_make_multichanneladd_cc (size_t itemsize);
size_t d_itemsize;
ucla_multichanneladd_cc (size_t itemsize);
public:
~ucla_multichanneladd_cc ();
int work (int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items);
// gr_sync_block overrides these to assist work
void forecast (int noutput_items, gr_vector_int &ninput_items_required);
int general_work (int noutput_items,
gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items);
};
#endif /* INCLUDED_UCLA_MULTICHANNELADD_CC_H */
|
tinyos-io/tinyos-3.x-contrib | berkeley/quanto/tos/lib/quanto/QuantoLog/QuantoLogStagedMyUART.h | #ifndef _QUANTO_MY_UART_H
#define _QUANTO_MY_UART_H
#include "RawUartMsg.h"
#include "my_message.h"
enum {
QLOG_CONTINUOUS = TRUE,
QLOG_ONESHOT = FALSE,
};
enum {
LOGSIZE = 700, //MAKE LOGSIZE A MULTIPLE OF N
N = (MY_MESSAGE_LENGTH-1)/sizeof(nx_entry_t), // N = 120/12 = 10
};
typedef nx_struct quanto_vlog_msg_t {
nx_uint8_t n;
nx_entry_t entries[N];
} quanto_vlog_msg_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libnxt/flash.c | <filename>nxtmote/misc/src/libnxt/flash.c
/**
* NXT bootstrap interface; NXT flash chip 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 <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include "error.h"
#include "lowlevel.h"
#include "samba.h"
#include "flash.h"
enum nxt_flash_commands
{
FLASH_CMD_LOCK = 0x2,
FLASH_CMD_UNLOCK = 0x4,
};
nxt_error_t
nxt_flash_wait_ready(nxt_t *nxt)
{
nxt_word_t flash_status;
do
{
NXT_ERR(nxt_read_word(nxt, 0xFFFFFF68, &flash_status));
/* Bit 0 is the FRDY field. Set to 1 if the flash controller is
* ready to run a new command.
*/
} while (!(flash_status & 0x1));
return NXT_OK;
}
static nxt_error_t
nxt_flash_alter_lock(nxt_t *nxt, int region_num,
enum nxt_flash_commands cmd)
{
nxt_word_t w = 0x5A000000 | ((64 * region_num) << 8);
w += cmd;
NXT_ERR(nxt_flash_wait_ready(nxt));
/* Flash mode register: FCMN 0x5, FWS 0x1
* Flash command register: KEY 0x5A, FCMD = clear-lock-bit (0x4)
* Flash mode register: FCMN 0x34, FWS 0x1
*/
NXT_ERR(nxt_write_word(nxt, 0xFFFFFF60, 0x00050100));
NXT_ERR(nxt_write_word(nxt, 0xFFFFFF64, w));
NXT_ERR(nxt_write_word(nxt, 0xFFFFFF60, 0x00340100));
return NXT_OK;
}
nxt_error_t
nxt_flash_lock_region(nxt_t *nxt, int region_num)
{
return nxt_flash_alter_lock(nxt, region_num, FLASH_CMD_LOCK);
}
nxt_error_t
nxt_flash_unlock_region(nxt_t *nxt, int region_num)
{
return nxt_flash_alter_lock(nxt, region_num, FLASH_CMD_UNLOCK);
}
nxt_error_t
nxt_flash_lock_all_regions(nxt_t *nxt)
{
int i;
for (i = 0; i < 16; i++)
NXT_ERR(nxt_flash_lock_region(nxt, i));
return NXT_OK;
}
nxt_error_t
nxt_flash_unlock_all_regions(nxt_t *nxt)
{
int i;
for (i = 0; i < 16; i++)
NXT_ERR(nxt_flash_unlock_region(nxt, i));
return NXT_OK;
}
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/daq/kernel-driver/pci1202.c | <reponame>tinyos-io/tinyos-3.x-contrib<gh_stars>1-10
/* PCI-1202 Service Module
Author: <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, 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. */
/* File level history (record changes for this file here.)
v 0.3.2 8 Jul 2003 by <NAME>
Fixed a bug about _align_minor().
v 0.3.1 16 Jan 2003 by <NAME>
Fixed the request io region bug that hanged the system.
v 0.3.0 8 Jan 2003 by <NAME>
Uses the dp->range[] instead of IO_RANGE.
v 0.2.0 11 Nov 2002 by <NAME>
Checks IO region before request.
Uses slab.h in place of malloc.h.
Complies to the kernel module license check.
v 0.1.1 16 May 2002 by <NAME>
Remove unused items: msg_ptr and msg[]
v 0.1.0 25 Oct 2001 by <NAME>
Re-filename to _pci1202.c (from pdaq1202.c.)
Change all "pdaq" to "ixpci."
v 0.0.0 3 May 2001 by <NAME>
create, blah blah... */
/* Mandatory */
#include <linux/kernel.h> /* ta, kernel work */
#include <linux/module.h> /* is a module */
/* Deal with CONFIG_MODVERSIONS that is defined in
/usr/include/linux/config.h (config.h is included by module.h) */
#ifdef CONFIG_MODVERSIONS
#define MODVERSIONS
#include <linux/modversions.h>
#endif
/* Additional */
#include <linux/fs.h>
/* use I/O ports */
#include <asm/io.h>
#include <linux/ioport.h>
/* Usermode access */
#include <asm/uaccess.h>
/* Local matter */
#include "ixpci_kernel.h"
#define MODULE_NAME "ixpci1202"
/* Register offsets */
/* Region 0 (NA) */
/* Region 1 */
#define _8254_TIMER_1 0x00
#define _8254_TIMER_2 0x04
#define _8254_TIMER_3 0x08
#define _8254_CONTROL_REGISTER 0x0c
/* Shorthands */
#define _8254C0 _8254_TIMER_1 /* take care the digit!! */
#define _8254C1 _8254_TIMER_2
#define _8254C2 _8254_TIMER_3
#define _8254CR _8254_CONTROL_REGISTER
/* Region 2 */
#define CONTROL_REGISTER 0x00
#define STATUS_REGISTER 0x00
#define AD_SOFTWARE_TRIGGER 0x04
/* Shorthands */
#define _CR CONTROL_REGISTER
#define _SR STATUS_REGISTER
#define _ADST AD_SOFTWARE_TRIGGER
/* Region 3 */
#define DI_PORT 0x00
#define DO_PORT 0x00
/* Shorthands */
#define _DI DI_PORT
#define _DO DO_PORT
/* Region 4 */
#define AD_DATA_PORT 0x00
#define DA_CHANNEL_1 0x00
#define DA_CHANNEL_2 0x04
/* Shorthands */
#define _AD AD_DATA_PORT
#define _DA1 DA_CHANNEL_1
#define _DA2 DA_CHANNEL_2
/* mask of registers (16-bit operation) */
#define _CR_MASK 0xbfdf
#define _SR_MASK 0x00ff
#define _AD_MASK 0x0fff
#define _DA1_MASK 0x0fff
#define _DA2_MASK 0x0fff
ixpci_kernel_t *dev;
#ifdef MODULE_LICENSE
MODULE_AUTHOR("<NAME> <<EMAIL>>");
MODULE_DESCRIPTION("ICPDAS PCI-series driver, PCI-1202 service module");
MODULE_LICENSE(ICPDAS_LICENSE);
#endif
static ixpci_kernel_t *find_board(int minor)
{
/* Locate a specific board by minor number */
ixpci_kernel_t *dp;
for (dp = dev; dp && dp->no != minor; dp = dp->next_f);
return dp;
}
static int write_register(ixpci_reg_t * reg, struct pci_dev *sdev)
{
/* Write to register
*
* Arguments:
* reg pointer to a structure ixpci_reg for register
* sdev pointer to a pci_dev structure.
*
* Returned: SUCCESS or FAILURE */
unsigned long timer = pci_resource_start(sdev, 1);
unsigned long control = pci_resource_start(sdev, 2);
unsigned long digital_io = pci_resource_start(sdev, 3);
unsigned long da = pci_resource_start(sdev, 4);
switch (reg->id) {
case IXPCI_8254C0:
outw((reg->value), timer + _8254C0);
break;
case IXPCI_8254C1:
outw((reg->value), timer + _8254C1);
break;
case IXPCI_8254C2:
outw((reg->value), timer + _8254C2);
break;
case IXPCI_8254CR:
outw((reg->value), timer + _8254CR);
break;
case IXPCI_CR:
outw((reg->value) & _CR_MASK, control + _CR);
break;
case IXPCI_ADST:
outw((reg->value), control + _ADST);
break;
case IXPCI_DO:
outw((reg->value), digital_io + _DO);
break;
case IXPCI_DA1:
outw((reg->value) & _DA1_MASK, da + _DA1);
break;
case IXPCI_DA2:
outw((reg->value) & _DA2_MASK, da + _DA2);
break;
default:
return -EINVAL;
}
return 0;
}
static int read_register(ixpci_reg_t * reg, struct pci_dev *sdev)
{
/* Read from register
*
* Arguments:
* reg pointer to structure ixpci_reg for register
* sdev pointer to a pci_dev structure.
*
* Returned: SUCCESS or FAILURE */
unsigned long timer = pci_resource_start(sdev, 1);
unsigned long control = pci_resource_start(sdev, 2);
unsigned long digital_io = pci_resource_start(sdev, 3);
unsigned long da = pci_resource_start(sdev, 4);
switch (reg->id) {
case IXPCI_8254C0:
reg->value = inw(timer + _8254C0);
break;
case IXPCI_8254C1:
reg->value = inw(timer + _8254C1);
break;
case IXPCI_8254C2:
reg->value = inw(timer + _8254C2);
break;
case IXPCI_SR:
reg->value = inw(control + _SR) & _SR_MASK;
break;
case IXPCI_DI:
reg->value = inw(digital_io + _DI);
break;
case IXPCI_AD:
reg->value = inw(da + _AD) & _AD_MASK;
break;
default:
return -EINVAL;
}
return 0;
}
static int time_span(int span, struct pci_dev *sdev)
{
/* Use the 8254 counter-2 to be the machine independent timer
* at the 8 MHz clock.
*
* Arguments:
* span micro-second (us) to be spanned
* sdev pointer to a pci_dev structure.
*
* Returned: SUCCESS or FAILURE */
unsigned long timer = pci_resource_start(sdev, 1);
unsigned long control = pci_resource_start(sdev, 2);
unsigned long sr;
unsigned counter;
unsigned char lbyte, hbyte;
int i;
if ((span > 8190) || (span == 0))
return -EOVERFLOW;
i = 0;
sr = control + _SR;
counter = span * 8;
lbyte = counter & 0xff;
hbyte = (counter >> 8) & 0xff;
outb(0xb0, timer + _8254CR);
outb(lbyte, timer + _8254C2);
outb(hbyte, timer + _8254C2);
while (inb(sr) & 0x01) {
if (i > 100000000)
return -ETIMEDOUT;
/* XXX - fix me for timeout */
++i;
}
return 0;
}
static int reset_dev(ixpci_kernel_t * dp)
{
unsigned long timer = pci_resource_start(dp->sdev, 1);
unsigned long control = pci_resource_start(dp->sdev, 2);
unsigned long digital_io = pci_resource_start(dp->sdev, 3);
unsigned long da = pci_resource_start(dp->sdev, 4);
/* stop timer 0 */
outb(0x34, timer + _8254CR);
outb(0x01, timer + _8254C0);
outb(0x00, timer + _8254C0);
/* stop timer 1 */
outb(0x74, timer + _8254CR);
outb(0x01, timer + _8254C1);
outb(0x00, timer + _8254C1);
/* stop timer 2 */
outb(0xb0, timer + _8254CR);
outb(0x01, timer + _8254C2);
outb(0x00, timer + _8254C2);
/* reset control register to
A/D channel 0
Gain control PGA = 1
Input range control = PGA (+/- 5V)
Reset the MagicScan controller
Assert the MagicScan handshake control bit (bit 13)
Clear FIFO */
outw(0x2000, control + _CR);
/* clear DO */
outw(0, digital_io + _DO);
/* clear DA */
outw(0, da + _DA1);
outw(0, da + _DA2);
/* did I leak anything? */
return 0;
}
static int pic_control(int command, struct pci_dev *sdev)
{
int value;
int cnt;
unsigned long control = pci_resource_start(sdev, 2);
value = inw(control + _SR) & _SR_MASK;
if ((value & 0x04) == 0)
/* Reset PIC */
outw(0xFFFF & _CR_MASK, control + _CR);
/* Wait for handshake */
cnt = 0;
value = inw(control + _SR) & _SR_MASK;
while ((value & 0x04) == 0) {
value = inw(control + _SR) & _SR_MASK;
if (++cnt > 65530)
return -ETIMEDOUT;
}
/* Send the command */
command &= 0xDFFF;
outw(command & _CR_MASK, control + _CR);
/* Wait for handshake */
cnt = 0;
value = inw(control + _SR) & _SR_MASK;
while (value & 0x04) {
value = inw(control + _SR) & _SR_MASK;
if (++cnt > 65530)
return -ETIMEDOUT;
}
command |= 0x2000;
outw(command & _CR_MASK, control + _CR);
/* Wait for handshake */
cnt = 0;
value = inw(control + _SR) & _SR_MASK;
while ((value & 0x04) == 0) {
value = inw(control + _SR) & _SR_MASK;
if (++cnt > 65530)
return -ETIMEDOUT;
}
return 0;
}
static int ixpci1202_ioctl(struct inode *inode,
struct file *file,
unsigned int ioctl_num, unsigned long ioctl_param)
{
/* (export)
*
* This function is called by ixpci.o whenever a process tries
* to do and IO control on IXPCI device file
*
* Arguments: read <linux/fs.h> for (*ioctl) of struct file_operations
*
* Returned: SUCCESS or FAILED */
ixpci_kernel_t *dp;
int res;
dp = find_board(iminor(inode));
if (!dp || !dp->open) return -ENODEV;
switch (ioctl_num) {
case IXPCI_GET_INFO:
{
ixpci_devinfo_t info;
ixpci_copy_devinfo(&info, dp);
if (copy_to_user((void __user *) ioctl_param, &info, sizeof(info)))
return -EFAULT;
break;
}
case IXPCI_READ_REG:
{
ixpci_reg_t reg;
int res;
if (copy_from_user(®, (void __user *) ioctl_param, sizeof(reg)))
return -EFAULT;
res = read_register(®, dp->sdev);
if (res)
return res;
if (copy_to_user((void __user *) ioctl_param, ®, sizeof(reg)))
return -EFAULT;
break;
}
case IXPCI_WRITE_REG:
{
ixpci_reg_t reg;
if (copy_from_user(®, (void __user *) ioctl_param, sizeof(reg)))
return -EFAULT;
return write_register(®, dp->sdev);
}
case IXPCI_TIME_SPAN:
return time_span((int) ioctl_param, dp->sdev);
case IXPCI_RESET:
return reset_dev(dp);
case IXPCI_PIC_CONTROL:
res = pic_control((int) ioctl_param, dp->sdev);
if (res) {
KMSG("%s: pic_control failed!!!!\n", MODULE_NAME);
return res;
}
break;
default:
return -EINVAL;
}
return 0;
}
static int ixpci1202_release(struct inode *inode, struct file *file)
{
/* (export)
*
* This function is called by ixpci.o whenever a process attempts to
* closes the device file. It doesn't have a return value in kernel
* version 2.0.x because it can't fail (you must always be able to
* close a device). In version 2.2.x it is allowed to fail.
*
* Arguments: read <linux/fs.h> for (*release) of struct file_operations
*
* Returned: none */
int minor;
ixpci_kernel_t *dp;
minor = iminor(inode);
dp = find_board(minor);
if (!dp)
return -ENODEV;
dp->open = 0;
module_put(THIS_MODULE);
return 0;
}
static int ixpci1202_open(struct inode *inode, struct file *file)
{
/* (export)
*
* This function is called by ixpci.o whenever a process attempts to
* open the device file of PCI-1202
*
* Arguments: read <linux/fs.h> for (*open) of struct file_operations
*
* Returned: none */
int minor;
ixpci_kernel_t *dp;
minor = iminor(inode);
dp = find_board(minor);
if (!dp) return -ENODEV;
if (!try_module_get(THIS_MODULE)) {
KMSG("Could not get THIS_MODULE\n");
return -EINVAL;
}
++(dp->open);
if (dp->open > 1) {
--(dp->open);
module_put(THIS_MODULE);
return -EBUSY;
/* if still opened by someone, get out */
}
return 0;
}
static struct file_operations fops = {
open: ixpci1202_open,
release: ixpci1202_release,
ioctl: ixpci1202_ioctl,
};
void cleanup_module()
{
/* cleanup this module */
int i;
ixpci_kernel_t *dp;
for (dp = dev; dp; dp = dp->next_f) {
KMSG("%s: Removing pci1202 card. Device %d:%d: ", MODULE_NAME,
ixpci_major, dp->no);
reset_dev(dp);
dp->fops = 0;
for (i = 0; i < PBAN; i++) {
if (!pci_resource_start(dp->sdev, i)
|| !pci_resource_len(dp->sdev, i))
continue;
release_region(pci_resource_start(dp->sdev, i),
pci_resource_len(dp->sdev, i));
}
/* remove file operations */
printk("done\n");
}
KMSG("%s has been removed.\n", MODULE_NAME);
}
int init_module()
{
/* initialize this module
*
* Arguments: none
*
* Returned:
* integer 0 for ok, otherwise failed (module can't be load) */
ixpci_kernel_t *dp;
int i;
struct resource *res;
/* align to first PCI-1202 in ixpci list */
for (dev = ixpci_dev; dev && dev->id != PCI_1202; dev = dev->next);
if (!dev) {
KMSG("%s: fail!\n", MODULE_NAME);
return -ENODEV;
}
/* initiate for each device (card) in family */
for (dp = dev; dp; dp = dp->next_f) {
KMSG("%s: Found pci1202 card. Device %d:%d: ", MODULE_NAME,
ixpci_major, dp->no);
/* request io region */
for (i = 0; i < PBAN; i++) {
if (!pci_resource_start(dp->sdev, i)
|| !pci_resource_len(dp->sdev, i))
continue;
res = request_region(pci_resource_start(dp->sdev, i),
pci_resource_len(dp->sdev, i), MODULE_NAME);
if (!res) {
/* Release all regions */
int j;
for (j = 0; j < i; j++)
release_region(pci_resource_start(dp->sdev, i),
pci_resource_len(dp->sdev, i));
KMSG("%s: Request region failed for 0x%08lx (size: 0x%08lx)\n",
MODULE_NAME, pci_resource_start(dp->sdev, i),
pci_resource_len(dp->sdev, i));
return -ENXIO;
}
}
dp->fops = &fops;
reset_dev(dp);
printk("done\n");
}
KMSG("%s ready.\n", MODULE_NAME);
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | diku/mcs51/tos/chips/nRF24E1/ionRF24E1.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.
*/
/**
*
* Provide nRF24E1 specific register maps
*
* @author <NAME> <<EMAIL>>
*/
#ifndef _H_ionRF24E1_H
#define _H_ionRF24E1_H
// Interrupt definitions these correspond to the orriginal 8051/8052 defs.
// we use the avr like __vector_? syntax will be mangled to something
// else later for Keil:
// void __vector_X(void) interrupt X
#define SIG_INTERRUPT0 __vector_0
#define SIG_TIMER0 __vector_1
#define SIG_INTERRUPT1 __vector_2
#define SIG_TIMER1 __vector_3
#define SIG_SERIAL __vector_4
#define SIG_TIMER2 __vector_5
#define SIG_ADC __vector_8
uint8_t volatile DPS __attribute((sfrAT0x86));
//sfr at 0x86 DPS;
uint8_t volatile P0_DIR __attribute((sfrAT0x94));
//sfr at 0xFD P0_DIR;
uint8_t volatile P1_DIR __attribute((sfrAT0x96));
//sfr at 0xFE P0_DIR;
uint8_t volatile P0_ALT __attribute((sfrAT0x95));
//sfr at 0x95 P0_ALT;
//Defined in io8051.h
//uint8_t volatile P1_ALT __attribute((sfrAT0x97));
//sfr at 0x97 P1_ALT;
uint8_t volatile RADIO __attribute((sfrAT0xA0));
//sfr at 0xA0 RADIO;
uint8_t volatile IP __attribute((sfrAT0xB8));
//sfr at 0xB8 IP;
uint8_t volatile EIE __attribute((sfrAT0xE8));
//sfr at 0xE8 EIE;
uint8_t volatile IE __attribute((sfrAT0xA8));
//sfr at 0xA8 IE;
/* IE */
//Defined in mcs51/io8051.h
//uint8_t volatile EA __attribute((sbitAT0xAF));
//sbit at IE^7 EA;
uint8_t volatile ET2 __attribute((sbitAT0xAD));
//sbit at IE^5 ET2;
uint8_t volatile ES __attribute((sbitAT0xAC));
//sbit at IE^4 ES;
uint8_t volatile ET1 __attribute((sbitAT0xAB));
//sbit at IE^3 ET1;
uint8_t volatile EX1 __attribute((sbitAT0xAA));
//sbit at IE^2 EX1;
uint8_t volatile ET0 __attribute((sbitAT0xA9));
//sbit at IE^1 ET0;
uint8_t volatile EX0 __attribute((sbitAT0xA8));
//sbit at IE^0 EX0;
/* RADIO */
#define SBIT_PWR_UP 0xA7
#define SBIT_DR2 0xA6
#define SBIT_CE 0xA6
#define SBIT_CLK2 0xA5
#define SBIT_DOUT2 0xA4
#define SBIT_CS 0xA3
#define SBIT_DR1 0xA2
#define SBIT_CLK1 0xA1
#define SBIT_DATA 0xA0
#define UART_OFFSET_NUM 0x30
#define UART_OFFSET_CHR 0x37
#endif // _H_ionRF24E1_H
|
tinyos-io/tinyos-3.x-contrib | tcd/powertossim-z/tinyos_files/tinyos-2.0.2/tos/lib/tossim/sim_gain.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_gain.h,v 1.1 2014/11/26 19:31:35 carbajor Exp $
#ifndef SIM_GAIN_H_INCLUDED
#define SIM_GAIN_H_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif
typedef struct gain_entry {
int mote;
double gain;
struct gain_entry* next;
} gain_entry_t;
void sim_gain_add(int src, int dest, double gain);
double sim_gain_value(int src, int dest);
bool sim_gain_connected(int src, int dest);
void sim_gain_remove(int src, int dest);
void sim_gain_set_noise_floor(int node, double mean, double range);
double sim_gain_sample_noise(int node);
double sim_gain_noise_mean(int node);
double sim_gain_noise_range(int node);
void sim_gain_set_sensitivity(double value);
double sim_gain_sensitivity();
gain_entry_t* sim_gain_first(int src);
gain_entry_t* sim_gain_next(gain_entry_t* e);
#ifdef __cplusplus
}
#endif
#endif // SIM_GAIN_H_INCLUDED
|
tinyos-io/tinyos-3.x-contrib | tub/tos/lib/tinycops/attributes/Attributes.h | /*
* Copyright (c) 2006, Technische Universitaet Berlin
* 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 Technische Universitaet Berlin 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.
*
* - Revision -------------------------------------------------------------
* $Revision: 1.1 $
* $Date: 2008/02/15 13:59:00 $
* @author: <NAME> <<EMAIL>>
* ========================================================================
*/
#ifndef __ATTRIBUTES_H
#define __ATTRIBUTES_H
#define EYESIFX_TEMPERATURE_ATTRIBUTE_ID 0
#define EYESIFX_LIGHT_ATTRIBUTE_ID 2
#define EYESIFX_RSSI_ATTRIBUTE_ID 3
#define MSP430_TEMPERATURE_ATTRIBUTE_ID 10
#define MSP430_VOLTAGE_ATTRIBUTE_ID 11
#define SENSIRION_TEMPERATURE_ATTRIBUTE_ID 12
#define SENSIRION_HUMIDITY_ATTRIBUTE_ID 13
#define PING_ATTRIBUTE_ID 17
#define DISCOVERY_ATTRIBUTE_ID 18
#define RANDOM_ATTRIBUTE_ID 19
#define FALSE_ATTRIBUTE_ID 20
#define RATE_ATTRIBUTE_ID 100
#define COUNT_ATTRIBUTE_ID 101
#define REBOOT_ATTRIBUTE_ID 104
#define ATTRIBUTE_NOTIFICATION_AMID 106
#define ATTRIBUTE_CLIENT_ID 107
#define ATTRIBUTE_SUBSCRIBER_ADDRESS 108
#define ATTRIBUTE_NOTIFICATION_HEADER 109
#define ATTRIBUTE_SEND_ON_DELTA 110
#define ATTRIBUTE_PARENT_ADDR 111
#define ATTRIBUTE_INTM_HOP_ADDR 112
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/stargate/rt_handler.h | #ifndef _RT_HANDLER_H_
#define _RT_HANDLER_H_
#include <stdint.h>
#include "rt_structs.h"
bool isFunctionalState(int8_t state);
void reportError(uint16_t nodeid, uint8_t error, rt_data _pdata);
void reportExit(rt_data _pdata);
int getNextSession();
int sendPathStartPacket(int id);
#endif
|
tinyos-io/tinyos-3.x-contrib | tinymulle/tos/platforms/mulle/hardware.h | <reponame>tinyos-io/tinyos-3.x-contrib<filename>tinymulle/tos/platforms/mulle/hardware.h<gh_stars>1-10
#ifndef __HARDWARE_H__
#define __HARDWARE_H__
#define MAIN_CRYSTAL_SPEED 10 /*MHz*/
#include "m16c62phardware.h" // Header file for the MCU
//#define ENABLE_STOP_MODE 0
#endif // __HARDWARE_H__
|
tinyos-io/tinyos-3.x-contrib | mc/raven/tos/chips/atm1284/timer/Atm128Timer.h |
/*
* Copyright (c) 2004-2005 Crossbow Technology, Inc. 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 Crossbow Technology 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 HOLDER 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.
*/
/*
* Copyright (c) 2007, Vanderbilt 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 copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* This file contains the configuration constants for the Atmega1284
* clocks and timers.
*
* @author <NAME>
* @author <NAME>
* @author <NAME> <<EMAIL>>
* @author <NAME>
*/
#ifndef _H_Atm128Timer_h
#define _H_Atm128Timer_h
/* Prescaler values for Timer/Counter 2 (8-bit asynchronous ) */
enum {
ATM128_CLK8_OFF = 0x0,
ATM128_CLK8_NORMAL = 0x1,
ATM128_CLK8_DIVIDE_8 = 0x2,
ATM128_CLK8_DIVIDE_32 = 0x3,
ATM128_CLK8_DIVIDE_64 = 0x4,
ATM128_CLK8_DIVIDE_128 = 0x5,
ATM128_CLK8_DIVIDE_256 = 0x6,
ATM128_CLK8_DIVIDE_1024 = 0x7,
};
/* Prescaler values for Timer/Counter 0 (8-bit) and 1, 3 (16-bit) */
enum {
ATM128_CLK16_OFF = 0x0,
ATM128_CLK16_NORMAL = 0x1,
ATM128_CLK16_DIVIDE_8 = 0x2,
ATM128_CLK16_DIVIDE_64 = 0x3,
ATM128_CLK16_DIVIDE_256 = 0x4,
ATM128_CLK16_DIVIDE_1024 = 0x5,
ATM128_CLK16_EXTERNAL_FALL = 0x6,
ATM128_CLK16_EXTERNAL_RISE = 0x7,
};
/* Common scales across both 8-bit and 16-bit clocks. */
enum {
AVR_CLOCK_OFF = 0,
AVR_CLOCK_ON = 1,
AVR_CLOCK_DIVIDE_8 = 2,
};
enum {
ATM128_TIMER_COMPARE_NORMAL = 0,
ATM128_TIMER_COMPARE_TOGGLE,
ATM128_TIMER_COMPARE_CLEAR,
ATM128_TIMER_COMPARE_SET
};
/* 8-bit Waveform Generation Modes */
enum {
ATM128_WAVE8_NORMAL = 0,
ATM128_WAVE8_PWM,
ATM128_WAVE8_CTC,
ATM128_WAVE8_PWM_FAST,
};
/* 16-bit Waveform Generation Modes */
enum {
ATM128_WAVE16_NORMAL = 0,
ATM128_WAVE16_PWM_8BIT,
ATM128_WAVE16_PWM_9BIT,
ATM128_WAVE16_PWM_10BIT,
ATM128_WAVE16_CTC_COMPARE,
ATM128_WAVE16_PWM_FAST_8BIT,
ATM128_WAVE16_PWM_FAST_9BIT,
ATM128_WAVE16_PWM_FAST_10BIT,
ATM128_WAVE16_PWM_CAPTURE_LOW,
ATM128_WAVE16_PWM_COMPARE_LOW,
ATM128_WAVE16_PWM_CAPTURE_HIGH,
ATM128_WAVE16_PWM_COMPARE_HIGH,
ATM128_WAVE16_CTC_CAPTURE,
ATM128_WAVE16_RESERVED,
ATM128_WAVE16_PWM_FAST_CAPTURE,
ATM128_WAVE16_PWM_FAST_COMPARE,
};
/* 8-bit Timer compare settings */
enum {
ATM128_COMPARE_OFF = 0, //!< compare disconnected
ATM128_COMPARE_TOGGLE, //!< toggle on match (PWM reserved
ATM128_COMPARE_CLEAR, //!< clear on match (PWM downcount)
ATM128_COMPARE_SET, //!< set on match (PWN upcount)
};
/* 8-bit Timer/Counter 0 Control Register A*/
typedef union
{
uint8_t flat;
struct {
uint8_t wgm00 : 1; //!< Waveform generation mode (low bit)
uint8_t wgm01 : 1; //!< Waveform generation mode (high bit)
uint8_t resv1 : 2; //!< Compare Match Output
uint8_t com0b0: 1; //!< Compare Match Output
uint8_t com0b1: 1; //!< Compare Match Output
uint8_t com0a0: 1; //!< Compare Match Output
uint8_t com0a1: 1; //!< Compare Match Output
} bits;
} Atm128_TCCR0A_t;
/* 8-bit Timer/Counter 0 Control Register B*/
typedef union
{
uint8_t flat;
struct {
uint8_t cs00 : 1; //!< Clock Select 0
uint8_t cs01 : 1; //!< Clock Select 1
uint8_t cs02 : 2; //!< Clock Select 2
uint8_t wgm02 : 1; //!< Waveform Generation Mode
uint8_t resv1 : 2; //!< Reserved
uint8_t foc0b : 1; //!< Force Output Compare B
uint8_t foc0a : 1; //!< Force Output Compare A
} bits;
} Atm128_TCCR0B_t;
/* Timer/Counter 0 Interrupt Mask Register */
typedef union
{
uint8_t flat;
struct {
uint8_t toie0 : 1; //!< Timer/Counter0 Overflow Interrupt Enable
uint8_t ocie0a: 1; //!< Timer/Counter0 Output Compare Match A Interrupt Enable
uint8_t ocie0e: 1; //!< Timer/Counter Output Compare Match B Interrupt Enable
uint8_t resv1 : 5; //!< Reserved
} bits;
} Atm128_TIMSK0_t;
/* Timer/Counter 0 Interrupt Flag Register*/
typedef union
{
uint8_t flat;
struct {
uint8_t tov0 : 1; //!< Timer/Counter0 Overflow Flag
uint8_t ocf0a : 1; //!< Timer/Counter 0 Output Compare A Match Flag
uint8_t ocf0b : 1; //!< Timer/Counter 0 Output Compare B Match Flag
uint8_t resv1 : 5; //!< Reserved
} bits;
} Atm128_TIFR0_t;
/* Asynchronous Status Register -- Timer2 */
typedef union
{
uint8_t flat;
struct {
uint8_t tcr2bub: 1; //!< Timer/Counter Control Register2 Update Busy
uint8_t tcr2aub: 1; //!< Timer/Counter Control Register2 Update Busy
uint8_t ocr2bub: 1; //!< Output Compare Register2 Update Busy
uint8_t ocr2aub: 1; //!< Output Compare Register2 Update Busy
uint8_t tcn2ub : 1; //!< Timer/Counter2 Update Busy
uint8_t as2 : 1; //!< Asynchronous Timer/Counter2 (off=CLK_IO,on=TOSC1)
uint8_t exclk : 1; //!< Enable External Clock Input
uint8_t resv1 : 1; //!< Reserved
} bits;
} Atm128_ASSR_t;
/* Timer/Counter 2 Control Register A*/
typedef union
{
uint8_t flat;
struct {
uint8_t wgm20 : 1; //!< Waveform Generation Mode
uint8_t wgm21 : 1; //!< Waveform Generation Mode
uint8_t resv1 : 2; //!< Reserved
uint8_t comb: 2; //!< Compare Output Mode for Channel B
uint8_t coma: 2; //!< Compare Output Mode for Channel A
} bits;
} Atm128_TCCR2A_t;
/* Timer/Counter 2 Control Register B*/
typedef union
{
uint8_t flat;
struct {
uint8_t cs : 3; //!< Clock Select
uint8_t wgm22 : 1; //!< Waveform Generation Mode
uint8_t resv1 : 2; //!< Reserved
uint8_t foc2b : 1; //!< Force Output Compare B
uint8_t foc2a : 1; //!< Force Output Compare A
} bits;
} Atm128_TCCR2B_t;
/* Timer/Counter 2 Interrupt Mask Register */
typedef union
{
uint8_t flat;
struct {
uint8_t toie : 1; //!< Timer/Counter2 Overflow Interrupt Enable
uint8_t ociea: 1; //!< Timer/Counter2 Output Compare Match A Interrupt Enable
uint8_t ocieb: 1; //!< Timer/Counter Output Compare Match B Interrupt Enable
uint8_t resv1 : 5; //!< Reserved
} bits;
} Atm128_TIMSK2_t;
/* Timer/Counter 2 Interrupt Flag Register */
typedef union
{
uint8_t flat;
struct {
uint8_t tov : 1; //!< Timer1 Overflow Flag
uint8_t ocfa : 1; //!< Timer1 Output Compare Flag A
uint8_t ocfb : 1; //!< Timer1 Output Compare Flag B
uint8_t resv1 : 5; //!< Reserved
} bits;
} Atm128_TIFR2_t;
/* Timer/Counter 1,3 Control Register A*/
typedef union
{
uint8_t flat;
struct {
uint8_t wgm01 : 2; //!< Waveform Generation Mode
uint8_t resv1 : 2; //!< Reserved
uint8_t comb : 2; //!< Compare Output Mode for Channel B
uint8_t coma : 2; //!< Compare Output Mode for Channel A
} bits;
} Atm128_TCCRA_t;
/* Timer/Counter 1,3 Control Register B*/
typedef union
{
uint8_t flat;
struct {
uint8_t cs : 3; //!< Clock Select
uint8_t wgm23 : 2; //!< Waveform Generation Mode
uint8_t resv1 : 1; //!< Reserved
uint8_t ices : 1; //!< Input Capture Edge Select
uint8_t icnc : 1; //!< Input Capture Noise Canceler
} bits;
} Atm128_TCCRB_t;
/* Timer/Counter 1,3 Control Register C*/
typedef union
{
uint8_t flat;
struct {
uint8_t resv1 : 6; //!< Reserved
uint8_t focb : 1; //!< Force Output Compare for Channel A
uint8_t foca : 1; //!< Force Output Compare for Channel A
} bits;
} Atm128_TCCRC_t;
/* Timer/Counter 1,3 Interrupt Mask Register */
typedef union
{
uint8_t flat;
struct {
uint8_t toie : 1; //!< Timer/Counter1 Overflow Interrupt Enable
uint8_t ociea: 1; //!< Timer/Counter1 Output Compare Match A Interrupt Enable
uint8_t ocieb: 1; //!< Timer/Counter1 Output Compare Match B Interrupt Enable
uint8_t resv1: 2; //!< Reserved
uint8_t icie : 1; //!< Timer/Counter1, Input Capture Interrupt Enable
uint8_t resv2 : 2; //!< Reserved
} bits;
} Atm128_TIMSK_t;
/* Timer/Counter 1,3 Interrupt Flag Register */
typedef union
{
uint8_t flat;
struct {
uint8_t tov : 1; //!< Timer1 Overflow Flag
uint8_t ocfa : 1; //!< Timer1 Output Compare Flag A
uint8_t ocfb : 1; //!< Timer1 Output Compare Flag B
uint8_t resv1: 2; //!< Reserved
uint8_t icf : 1; //!< Timer1 Input Capture Flag
uint8_t resv2: 2; //!< Reserved
} bits;
} Atm128_TIFR_t;
/* General Timer/Counter Control Register */
typedef union
{
uint8_t flat;
struct {
uint8_t psrsync: 1; //!< Prescaler Reset for Synchronous Timer/Counters 0,1,3
uint8_t psrasy : 1; //!< Prescaler Reset Timer/Counter2
uint8_t resv1 : 5; //!< Reserved
uint8_t tsm : 1; //!< Timer/Counter Synchronization Mode
} bits;
} Atm128_GTCCR_t;
// Read/Write these 16-bit Timer registers
// Access as bytes. Read low before high. Write high before low.
typedef uint8_t Atm128_TCNT1H_t; //!< Timer1 Register
typedef uint8_t Atm128_TCNT1L_t; //!< Timer1 Register
typedef uint8_t Atm128_TCNT3H_t; //!< Timer3 Register
typedef uint8_t Atm128_TCNT3L_t; //!< Timer3 Register
/* Contains value to continuously compare with Timer1 */
typedef uint8_t Atm128_OCR1AH_t; //!< Output Compare Register 1A
typedef uint8_t Atm128_OCR1AL_t; //!< Output Compare Register 1A
typedef uint8_t Atm128_OCR1BH_t; //!< Output Compare Register 1B
typedef uint8_t Atm128_OCR1BL_t; //!< Output Compare Register 1B
/* Contains value to continuously compare with Timer3 */
typedef uint8_t Atm128_OCR3AH_t; //!< Output Compare Register 3A
typedef uint8_t Atm128_OCR3AL_t; //!< Output Compare Register 3A
typedef uint8_t Atm128_OCR3BH_t; //!< Output Compare Register 3B
typedef uint8_t Atm128_OCR3BL_t; //!< Output Compare Register 3B
/* Contains counter value when event occurs on ICPn pin. */
typedef uint8_t Atm128_ICR1H_t; //!< Input Capture Register 1
typedef uint8_t Atm128_ICR1L_t; //!< Input Capture Register 1
typedef uint8_t Atm128_ICR3H_t; //!< Input Capture Register 3
typedef uint8_t Atm128_ICR3L_t; //!< Input Capture Register 3
/* Resource strings for timer 1 and 3 compare registers */
#define UQ_TIMER1_COMPARE "atm128.timer1"
#define UQ_TIMER3_COMPARE "atm128.timer3"
#endif //_H_Atm128Timer_h
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/lib/blackbook/core/Blackbook.h | <filename>rincon/tos/lib/blackbook/core/Blackbook.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 BLACKBOOK_H
#define BLACKBOOK_H
/**
* Blackbook Definitions v.6
* @author <NAME> (<EMAIL>)
*/
#include "BlackbookConst.h"
#include "BDictionary.h"
#define UQ_BDICTIONARY "BDictionary"
#define UQ_BFILEDELETE "BFileDelete"
#define UQ_BFILEDIR "BFileDir"
#define UQ_BFILEREAD "BFileRead"
#define UQ_BFILEWRITE "BFileWrite"
#ifndef BLACKBOOK_TOTAL_ERASEBLOCKS
#define BLACKBOOK_TOTAL_ERASEBLOCKS 16
#endif
/**
* This is a complete name of a file that we can pass around Blackbook
* and not worry about whether or not enough bytes were allocated for
* the filename.
*/
typedef struct filename_t {
/** The name of a file */
char getName[FILENAME_LENGTH];
} filename_t;
/** flashnode_t flags */
typedef enum {
NO_FLAGS = 0x0,
DICTIONARY = 0x1,
RESERVED0 = 0x2,
RESERVED1 = 0x4,
RESERVED2 = 0x8,
RESERVED3 = 0x10,
RESERVED4 = 0x20,
RESERVED5 = 0x40,
RESERVED6 = 0x80,
} flashnode_flags_enum;
/**
* This is the nodemeta information kept at the start of each
* flashnode_t on flash
*/
typedef struct nodemeta_t {
/** Magic number to detect valid metadata. This is after dataCrc for finalizing */
uint16_t magicNumber;
/** Length of the space reserved for this flashnode_t on flash */
uint32_t reserveLength;
/** The CRC of the filename this flashnode_t is associated with */
uint16_t filenameCrc;
/** The element of the file this flashnode_t represents, 0 for the first flashnode_t */
uint16_t fileElement;
/** Node flags */
flashnode_flags_enum nodeflags;
} nodemeta_t;
/**
* This is the filemeta information located directly after nodemeta
* information for the first flashnode_t of a file on flash
*/
typedef struct filemeta_t {
/** Name of the file */
struct filename_t name;
} filemeta_t;
/** Possible flashnode_t States */
typedef enum {
/** The flashnode_t can be used by anything */
NODE_EMPTY,
/** This is a special constructing flashnode_t that is to be deleted if the mote is rebooted */
NODE_CONSTRUCTING,
/** The flashnode_t is valid and can be written to */
NODE_VALID,
/** This flashnode_t is valid and cannot be written to */
NODE_LOCKED,
/** This flashnode_t exists virtually, but no info has been written to flash */
NODE_TEMPORARY,
/** This flashnode_t was found on flash, but is not valid */
NODE_DELETED,
/** This flashnode_t is valid and booting */
NODE_BOOTING,
} flashnode_state_enum;
/**
* This is the flashnode_t information kept in memory for each node
*/
typedef struct flashnode_t {
/** The address of this flashnode_t on flash */
uint32_t flashAddress;
/** The next flashnode_t in the file after this one */
struct flashnode_t *nextNode;
/** The total length of valid data written to this flashnode_t */
uint16_t dataLength;
/** The total length of space reserved for this flashnode_t */
uint32_t reserveLength;
/** The current CRC of the flashnode_t */
uint16_t dataCrc;
/** The CRC of the filename from the file this flashnode_t is associated with */
uint16_t filenameCrc;
/** The state of the flashnode_t */
flashnode_state_enum nodestate;
/** flashnode flags */
flashnode_flags_enum nodeflags;
/** The index this flashnode_t belongs to in its entire file */
uint8_t fileElement;
} flashnode_t;
/** Possible file_t States */
typedef enum {
/** This file index is empty and can be used by anybody */
FILE_EMPTY,
/** This file exists virtually, but no info has been written to flash */
FILE_TEMPORARY,
/** This file is valid but not being used */
FILE_IDLE,
/** The nodes in this file is open for reading */
FILE_READING,
/** The nodes in this file are open for writing */
FILE_WRITING,
FILE_READING_AND_WRITING,
} file_state_enum;
/**
* This is the information kept for each file in RAM memory
*/
typedef struct file_t {
/** The first flashnode_t of this file */
flashnode_t *firstNode;
/** The calculated crc of the file, so we don't have to calculate it every time */
uint16_t filenameCrc;
/** The state of this file */
file_state_enum filestate;
} file_t;
/**
* This is the sector information kept
* in RAM for every sector on flash.
*/
typedef struct flasheraseblock_t {
/** The starting erase unit in the volume */
uint16_t baseEraseUnit;
/** Next write unit number available for writing */
uint16_t writeUnit;
/** Total number of erase units in this block */
uint16_t totalEraseUnits;
/** Total amount of valid nodes on this sector */
uint16_t totalNodes;
/** This erase unit's ID */
uint8_t index;
/** FALSE if this sector has no open write files */
bool inUse;
} flasheraseblock_t;
/**
* This is the checkpoint struct that is inserted
* into a key-value pair in the Checkpoint file
*/
typedef struct checkpoint_t {
/** Node's filename CRC for verification */
uint16_t filenameCrc;
/** The CRC of the data contained up to the dataLength of the flashnode_t */
uint16_t dataCrc;
/** Length of the node's data */
uint16_t dataLength;
/** TRUE if this flashnode_t is still available for writing */
bool writable;
} checkpoint_t;
/** Magic Words */
enum {
/** No flashnode_t exists at this point in the flash */
META_EMPTY = 0xFFFF, // binary 1111
/** This flashnode_t is being constructed. If this is found on boot, delete the flashnode_t */
META_CONSTRUCTING = 0x7777, // binary 0111
/** This flashnode_t is finalized on flash and all information is local */
META_VALID = 0x3333, // binary 0011
/** This flashnode_t is deleted, mark up the SectorMap and move on */
META_INVALID = 0x1111, // binary 0001
/** This is the type of data you'll find when a dataCrc is unfinalized */
UNFINALIZED_CRC = 0xFFFF,
/** This is the type of data you'll find when a dataLength is unfinalized */
UNFINALIZED_DATA = 0xFFFF,
};
/** Global state machine for blackbook */
enum {
S_BLACKBOOK_IDLE = 0,
/** The file system is booting */
S_BOOT_BUSY,
/** The file system is recovering nodes */
S_BOOT_RECOVERING_BUSY,
/** The dictionary is in use */
S_DICTIONARY_BUSY,
/** Write: The general file writer is in use */
S_WRITE_BUSY,
/** Write: The file writer is saving */
S_WRITE_SAVE_BUSY,
/** Write: The file writer is closing */
S_WRITE_CLOSE_BUSY,
/** The file reader is in use */
S_READ_BUSY,
/** The file dir is in use */
S_DIR_BUSY,
/** The file delete is in use */
S_DELETE_BUSY,
/** The garbage collector is running */
S_GC_BUSY,
BLACKBOOK_STATE = unique("State"),
};
enum {
INTERNAL_DICTIONARY = unique(UQ_BDICTIONARY),
};
#endif
|
tinyos-io/tinyos-3.x-contrib | rincon/apps/tests/TestParameterStorage/ComponentA.h |
/**
* @author <NAME>
* @author <NAME> (<EMAIL>)
*/
#ifndef COMPONENTA_H
#define COMPONENTA_H
#define UQ_COMPONENTA_EXTENSION "componentA.ExtendMetadata"
typedef nx_struct cc5000_metadata_t {
nx_uint8_t tx_power;
nx_uint8_t rssi;
nx_uint8_t lqi;
nx_bool crc;
nx_bool ack;
nx_uint16_t time;
nx_uint8_t extendedParameters[uniqueCount(UQ_COMPONENTA_EXTENSION)];
} cc5000_metadata_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | wsu/telosw/ADC/Accelerometer.h | #ifndef __ACCELEROMETER_H
#define __ACCELEROMETER_H
enum{
QUEUE_SIZE = 8,
ADDRESS_DEVID = 0x00,
ADDRESS_THRESH_TAP = 0x1D,
ADDRESS_OFSX = 0x1E,
ADDRESS_OFSY = 0x1F,
ADDRESS_OFSZ = 0x20,
ADDRESS_DUR = 0x21,
ADDRESS_LATENT = 0x22,
ADDRESS_WINDOW = 0x23,
ADDRESS_THRESH_ACT = 0x24,
ADDRESS_THRESH_INACT = 0x25,
ADDRESS_TIME_INACT = 0x26,
ADDRESS_ACT_INACT_CTL = 0x27,
ADDRESS_THRESH_FF = 0x28,
ADDRESS_TIME_FF = 0x29,
ADDRESS_TAP_AXES = 0x2A,
ADDRESS_ACT_TAP_STATUS = 0x2B,
ADDRESS_BW_RATE = 0x2C,
ADDRESS_POWER_CTL = 0x2D,
ADDRESS_INT_ENABLE = 0x2E,
ADDRESS_INT_MAP = 0x2F,
ADDRESS_INT_SOURCE = 0x30,
ADDRESS_DATA_FORMAT = 0x31,
ADDRESS_DATAX0 = 0x32,
ADDRESS_DATAX1 = 0x33,
ADDRESS_DATAY0 = 0x34,
ADDRESS_DATAY1 = 0x35,
ADDRESS_DATAZ0 = 0x36,
ADDRESS_DATAZ1 = 0x37,
ADDRESS_FIFO_CTL = 0x38,
ADDRESS_FIFO_STATUS = 0x39,
DATA_THRESH_TAP = 0x1,
DATA_OFSX = 0x0,
DATA_OFSY = 0x0,
DATA_OFSZ = 0x0,
DATA_DUR = 0x2,
DATA_LATENT = 0x2,
DATA_WINDOW = 0x2,
DATA_THRESH_ACT = 0x30,
DATA_THRESH_INACT = 0x20,
DATA_TIME_INACT = 0x05,
DATA_ACT_INACT_CTL = 0xFF,
DATA_THRESH_FF = 0x07,
DATA_TIME_FF = 0x20,
DATA_TAP_AXES = 0x07,
DATA_BW_RATE = 0x0A,
DATA_POWER_CTL_STANDBY = 0x10,
DATA_POWER_CTL_MEASURE = 0x08,
DATA_INT_ENABLE = 0x18,
DATA_INT_MAP = 0x10,
DATA_DATA_FORMAT = 0x80,
DATA_FIFO_CTL = 0x00,
ADDRESS_WRITE = 0xA6,
ADDRESS_READ = 0xA7
};
typedef struct acc {
uint16_t x;
uint16_t y;
uint16_t z;
}acc_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/tinyos/fluxconst.h | <reponame>tinyos-io/tinyos-3.x-contrib<filename>eon/eon/src/runtime/tinyos/fluxconst.h
#ifndef FLUXCONST_H_INCLUDED
#define FLUXCONST_H_INCLUDED
//define error codes
#define ERR_OK 0
#define ERR_NOMEMORY 1
#define ERR_FREEMEM 2
#define ERR_QUEUE 3
#define ERR_TRANSLATE 4
#define ERR_RTDATA 5
#define ERR_SRC 6
#define ERR_NONODE 7
#define ERR_USR 10
#endif
|
tinyos-io/tinyos-3.x-contrib | diku/mcs51/tos/chips/mcs51/timer/mcs51-timer.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_mcs51_timer_H
#define _H_mcs51_timer_H
typedef enum {
MCS51_TIMER_MODE_13BIT = 0,
MCS51_TIMER_MODE_16BIT = 1,
MCS51_TIMER_MODE_8BIT_RELOAD = 2,
MCS51_TIMER_MODE_DOUBLE_8BIT = 3
} mcs51_timer_mode_t;
typedef enum {
MCS51_TIMER_SRC_SYSCLK = 0,
MCS51_TIMER_SRC_EXT = 1
} mcs51_timer_src_t;
enum {
MCS51_TCON_TF1 = 7,
MCS51_TCON_TR1 = 6,
MCS51_TCON_TF0 = 5,
MCS51_TCON_TR0 = 4,
MCS51_TCON_IE1 = 3,
MCS51_TCON_IT1 = 2,
MCS51_TCON_IE0 = 1,
MCS51_TCON_IT0 = 0
};
enum {
MCS51_TMOD_T0MODE_MASK = 0x03,
MCS51_TMOD_T1MODE_MASK = 0x30,
MCS51_TMOD_GATE1 = 7,
MCS51_TMOD_CT1 = 6,
MCS51_TMOD_M1M1 = 5,
MCS51_TMOD_T1M0 = 4,
MCS51_TMOD_GATE0 = 3,
MCS51_TMOD_CT0 = 2,
MCS51_TMOD_M0M1 = 1,
MCS51_TMOD_T0M0 = 0
};
#endif //_H_mcs51_timer_H
|
tinyos-io/tinyos-3.x-contrib | diku/common/lib/simplemac/packet.h | /*
Copyright (C) 2004 <NAME> <<EMAIL>>
Copyright (C) 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 PACKET_H
#define PACKET_H
#define PACKET_MAX_PAYLOAD 122
typedef uint16_t mac_addr_t;
typedef uint8_t ieee_mac_addr_t[8];
/* Frame types */
enum fcf_stuff {
FCF_FT_BEACON = 0x0000,
FCF_FT_DATA = 0x0001,
FCF_FT_ACK = 0x0002,
FCF_FT_MAC_COMMAND = 0x0003,
FCF_FT_MASK = 0x0007,
/* Frame Control Field bits */
FCF_SECENC = 0x0008,
FCF_FRAMEPENDING = 0x0010,
FCF_ACKREQ = 0x0020,
FCF_INTRAPAN = 0x0040,
/* Addressing modes */
FCF_DST_NO_ADDR = 0x0000,
FCF_DST_SHORT_ADDR = 0x0800,
FCF_DST_LONG_ADDR = 0x0C00,
FCF_DST_ADDR_MASK = 0x0C00,
FCF_SRC_NO_ADDR = 0x0000,
FCF_SRC_SHORT_ADDR = 0x8000,
FCF_SRC_LONG_ADDR = 0xC000,
FCF_SRC_ADDR_MASK = 0xC000,
FCS_CRC_OK_MASK = 0x80,
FCS_CORRELATION_MASK = 0x7F,
};
typedef struct {
int8_t rssi;
uint8_t correlation;
} fsc_t;
struct packet
{
uint8_t length;
uint16_t fcf;
uint8_t data_seq_no;
mac_addr_t dest;
mac_addr_t src;
uint8_t data[PACKET_MAX_PAYLOAD - 2 * sizeof(mac_addr_t)];
fsc_t fcs;
#ifdef __i386__
} __attribute__ ((packed));
#else
};
#endif
typedef struct packet packet_t;
//#include "../treeRoute/treePacket.h"
#endif
|
tinyos-io/tinyos-3.x-contrib | ethz/snpk/apps/tests/SyncMac/syncmac.h | <reponame>tinyos-io/tinyos-3.x-contrib<gh_stars>1-10
#ifndef SYNCMACTEST_H
#define SYNCMACTEST_H
#include "AM.h"
#ifndef SYNCMAC_MIN_NEIGHBOURS
#define SYNCMAC_MIN_NEIGHBOURS 3
#endif
typedef nx_struct beacon_msg {
nx_am_addr_t id;
nx_uint8_t data[10];
} beacon_msg_t;
typedef nx_struct unicast_msg {
nx_am_addr_t id;
nx_uint8_t data[10];
} unicast_msg_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/quanto/tools/quanto/labjack/QuantoLogger.h | <filename>berkeley/quanto/tools/quanto/labjack/QuantoLogger.h<gh_stars>1-10
#define NUM_CHANNELS 4
typedef struct channelopts_t {
uint8_t channel;
uint8_t options;
}
typedef struct streamconfigmsg_t {
uint8_t checksum8;
uint8_t command;
uint8_t numchansplusthree;
uint8_t extcommand;
uint16_t checksum16;
uint8_t numchannels;
uint8_t resolution;
uint8_t settlingtime;
uint8_t scanconfig;
uint16_t scaninterval;
struct channelopts_t [NUM_CHANNELS];
} streamconfigmsg_t;
|
tinyos-io/tinyos-3.x-contrib | iowa/T2.tsync/IAtsync/T2spy.c | <reponame>tinyos-io/tinyos-3.x-contrib
/*
* Copyright (c) 2007 University of Iowa
* 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 University of Iowa 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.
*/
/**
* Timesync suite of interfaces, components, testing tools, and documents.
* @author <NAME>
* Development supported in part by NSF award 0519907.
*/
//--EOCpr712 (do not remove this line, which terminates copyright include)
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <strings.h>
#include <errno.h>
#include <sys/poll.h>
// primitive Listen program (to be used with serialforwarder, ie.
// the 'sf' program in $TOSDIR/../tools/src
// **** NICE ENHANCEMENTS WOULD BE ********
// 1. automatic start of the sf program;
// 2. add command-line parameters to set TPS, debug options
// 3. allow commands to be issued for fault injection, etc.
//
// Emulate TinyOS/NesC programming environment
#define FALSE 0
#define TRUE 1
/***** NOTE: need to define by hand because of __attribute__ ((packed)) ***/
typedef struct micaTOS_Msg
{
/* The following fields are transmitted/received by serial forwarder. */
uint8_t pad;
uint8_t fcf[2];
uint8_t dest[2];
uint8_t length;
uint8_t pad2;
uint8_t type;
uint8_t data[28];
} micaTOS_Msg;
typedef micaTOS_Msg * micaTOS_MsgPtr;
typedef struct telosTOS_Msg
{
uint8_t pad;
uint8_t fcf[2];
uint8_t dest[2];
uint8_t length;
uint8_t pad2;
uint8_t type;
int8_t data[28];
} telosTOS_Msg;
typedef telosTOS_Msg * telosTOS_MsgPtr;
enum { AM_BEACON=40,
AM_BEACON_PROBE=41,
AM_PROBE_ACK=42,
AM_PROBE_DEBUG=43,
AM_NEIGHBOR=44,
AM_NEIGHBOR_DEBUG=45,
AM_SKEW=47,
AM_UART=50
};
typedef struct beaconMsg {
uint16_t sndId; // Id of sender
int16_t prevDiff; // difference of most recent received Beacon
uint8_t Local[6]; // local clock of sender (48 bit, H and L)
uint8_t Virtual[6]; // virtual time of sender (48 bit, H and L)
uint8_t Xor[6]; // XOR of the above two clocks
uint8_t mode; // sender's mode
uint8_t NbrSize; // neighborhood size of sender
uint8_t Delay[4]; // processing and MAC delay of sending beacon
} beaconMsg;
typedef beaconMsg * beaconMsgPtr;
typedef struct beaconProbeAck {
uint16_t count;
uint16_t sndId; // id of sender
uint8_t Local[6]; // local clock for Ack (48 bit, H and L)
uint8_t Virtual[6]; // virtual time for Ack (48 bit, H and L)
float skew; // current skew adjustment amount
float calibRatio; // reported OTime.calibrate() value
} beaconProbeAck;
typedef beaconProbeAck * beaconProbeAckPtr;
// Structure of Neighborhood Message
typedef struct neighborMsg {
uint16_t sndId; // Id of sender
uint16_t nodes[12]; // neighbors heard from recently
} neighborMsg;
typedef neighborMsg * neighborMsgPtr;
// DebugMsg is generated only in testing versions
typedef struct beaconDebugMsg {
uint16_t sndId; // id of sender
uint8_t type; // a one-byte "type" of debugging
uint8_t stuff[25]; // anything can go here
} beaconDebugMsg; // 28 bytes of debugging data
typedef beaconDebugMsg * beaconDebugMsgPtr;
// Skew diffusion/gossip message
typedef struct skewMsg {
uint16_t sndId; // Id of sender
uint16_t rootId; // Id of "root" initiator of diffusion
uint16_t minId; // Id of node with minimum known skew
uint8_t initStamp[6]; // Vclock of initiation
float skewMin; // minimum known skew
uint8_t seqno; // sequence number (for repeats)
} skewMsg;
typedef skewMsg * skewMsgPtr;
enum { MICA128 = 1, TELOS = 2, MICAZ = 3 }; // types of motes
char motetype = 0;
uint32_t TPS;
struct timeval startT; // time at start of Spy run
/***** Convert a mote (atmel) uint32_t *********/
uint32_t moteInt(uint8_t * g) {
uint32_t b;
b = (g[0]&0xff);
b += (g[1]&0xff) << 8;
b += (g[2]&0xff) << 16;
b += (g[3]&0xff) << 24;
return b;
}
/***** Convert a mote nx_uint32_t *********/
uint32_t nx_moteInt(uint8_t * g) {
uint32_t b;
b = (g[3]&0xff);
b += (g[2]&0xff) << 8;
b += (g[1]&0xff) << 16;
b += (g[0]&0xff) << 24;
return b;
}
/******** show raw hex data ***********/
void showhex( void * p, int n ) {
int i;
uint8_t * c = (uint8_t *) p;
for (i=0;i<n;i++) printf("%2.2x ",*(c+i));
}
/**** Write TOS_Msg to Socket *******/
void putStreamMica( int socket, micaTOS_MsgPtr p ) {
int i, r;
uint8_t n;
char * s;
extern int errno;
n = p->length + sizeof(micaTOS_Msg) - 29;
s = (char *) p;
r = write(socket, &n, 1);
// printf("sent %x\n",n);
if (r < 0) { perror("putStream error"); exit(errno); }
for (i = 0; i < n; i++) {
r = write(socket, &s[i], 1);
// printf("sent %x\n",*(s+i));
if (r < 0) { perror("putStream error"); exit(errno); }
}
}
/**** Read Stream from Socket ******/
void getStreamMica( int socket, micaTOS_MsgPtr p ) {
int i, r;
char * s;
uint8_t n;
extern int errno;
s = (char *) p;
// fprintf(stderr,"trying to read from socket\n");
r = read(socket, &n, 1);
if (r < 0) { perror("getStream error"); exit(errno); }
if (r == 0) { fprintf(stderr,"connection broken!\n"); exit(0); }
fprintf(stderr,"got message for %d bytes\n",n-6);
// now read the data
if ( n > sizeof(micaTOS_Msg) ) {
fprintf(stderr,"wierd message for %d bytes returned\n",n);
exit(1);
}
for (i = 0; i < n; i++) {
r = read(socket, &s[i], 1);
if (r < 0) { perror("getStream error"); exit(errno); }
if (r == 0) { fprintf(stderr,"connection broken!\n"); exit(0); }
}
showhex(s,n);
printf("\n");
return;
}
/**** Read Stream from Socket ******/
void getStreamTelos( int socket, telosTOS_MsgPtr p ) {
int i, r;
char * s;
uint8_t n;
extern int errno;
s = (char *) p;
r = read(socket, &n, 1);
if (r < 0) { perror("getStream error"); exit(errno); }
if (r == 0) { fprintf(stderr,"connection broken!\n"); exit(0); }
// printf("got message for %d byte payload ",n-8);
// now read the data
if ( n > sizeof(telosTOS_Msg) ) {
fprintf(stderr,"wierd message for %d bytes returned\n",n);
exit(1);
}
for (i = 0; i < n; i++) {
r = read(socket, &s[i], 1);
if (r < 0) { perror("getStream error"); exit(errno); }
if (r == 0) { fprintf(stderr,"connection broken!\n"); exit(0); }
}
// showhex(s,n);
// printf("\n");
return;
}
/**** Exchange SF Protocol Number ******/
void exchange( int socket ) {
int i, r;
char s[2];
extern int errno;
for (i = 0; i < 2; i++) {
r = read(socket, &s[i], 1);
if (r < 0) { perror("getExchange error"); exit(errno); }
if (r == 0) { fprintf(stderr,"connection broken!\n"); exit(0); }
}
if ( !(s[0] == 'U' & s[1] == ' ') ) {
fprintf(stderr,"SFProtocol exchange failed\n"); exit(0);
}
s[1] = ' ';
for (i = 0; i < 2; i++) {
r = write(socket, &s[i], 1);
if (r < 0) { perror("putExchange error"); exit(errno); }
}
}
void displayNeighbor(neighborMsgPtr p) {
int i;
struct timeval T;
// show elapsed time since start of run
gettimeofday(&T,NULL);
T.tv_sec -= startT.tv_sec;
if (T.tv_usec >= startT.tv_usec) T.tv_usec -= startT.tv_usec;
else {
T.tv_sec--;
T.tv_usec += 1000000;
T.tv_usec -= startT.tv_usec;
}
printf("t=%d.%03d ",T.tv_sec,T.tv_usec/1000);
printf("sndId=%d ",p->sndId);
printf("nbrs=[ ");
for (i=0;i<12;i++) printf("%d ",p->nodes[i]);
printf("]\n");
}
void displayProbeDebug(beaconDebugMsgPtr p) {
int i;
struct timeval T;
// show elapsed time since start of run
gettimeofday(&T,NULL);
T.tv_sec -= startT.tv_sec;
if (T.tv_usec >= startT.tv_usec) T.tv_usec -= startT.tv_usec;
else {
T.tv_sec--;
T.tv_usec += 1000000;
T.tv_usec -= startT.tv_usec;
}
printf("t=%d.%03d Pdbg ",T.tv_sec,T.tv_usec/1000);
printf("sndId=%d ",p->sndId);
showhex(p->stuff,24);
printf("\n");
}
void displayNeighborDebug(beaconDebugMsgPtr p) {
int i;
struct timeval T;
// show elapsed time since start of run
gettimeofday(&T,NULL);
T.tv_sec -= startT.tv_sec;
if (T.tv_usec >= startT.tv_usec) T.tv_usec -= startT.tv_usec;
else {
T.tv_sec--;
T.tv_usec += 1000000;
T.tv_usec -= startT.tv_usec;
}
printf("t=%d.%03d Ndbg ",T.tv_sec,T.tv_usec/1000);
printf("sndId=%d ",p->sndId);
showhex(p->stuff,24);
printf("\n");
}
void displaySkew(skewMsgPtr p) {
int i;
double V;
struct timeval T;
// show elapsed time since start of run
gettimeofday(&T,NULL);
T.tv_sec -= startT.tv_sec;
if (T.tv_usec >= startT.tv_usec) T.tv_usec -= startT.tv_usec;
else {
T.tv_sec--;
T.tv_usec += 1000000;
T.tv_usec -= startT.tv_usec;
}
printf("t=%d.%03d Skewcast ",T.tv_sec,T.tv_usec/1000);
printf("sndId=%d ",p->sndId);
printf("rootId=%d ",p->rootId);
printf("minId=%d ",p->minId);
printf("seqno=%d ",p->seqno);
// display init time in skew message
V = (double) *(uint16_t *)p->initStamp;
V *= 4294967295.0 / (double) TPS;
V += (double) moteInt(&p->initStamp[2]) / (double) TPS;
printf("initStamp=%f ",V);
// minimum known skew
printf("skewMin=%e\n",p->skewMin);
}
void displayProbeAck(beaconProbeAckPtr p ) {
int i, j, k, n;
int id1, id2;
double L, V, s, y, mean;
struct timeval T;
struct recordProbe {
int id;
int seqno;
double Vclock;
float skew;
float calibRatio;
};
static struct recordProbe R[50] = { -1, -1 };
// show elapsed time since start of run
gettimeofday(&T,NULL);
T.tv_sec -= startT.tv_sec;
if (T.tv_usec >= startT.tv_usec) T.tv_usec -= startT.tv_usec;
else {
T.tv_sec--;
T.tv_usec += 1000000;
T.tv_usec -= startT.tv_usec;
}
// printf("t=%d.%03d ",T.tv_sec,T.tv_usec/1000);
// show sequence number, id
// printf("-- probeAck: count=%d id=%d ",p->count,p->sndId);
// display local time in beacon message
L = (double) *(uint16_t *)p->Local;
L *= 4294967295.0 / (double) TPS;
L += (double) moteInt(&p->Local[2]) / (double) TPS;
// display virtual time in beacon message
V = (double) *(uint16_t *)p->Virtual;
V *= 4294967295.0 / (double) TPS;
V += (double) moteInt(&p->Virtual[2]) / (double) TPS;
// printf(" Ltime=%f Vtime=%f ",L,V);
// show current skew adjustment
// printf(" skew=%d\n",p->skew);
// check for this probe ack being a new one
if (p->count != R[0].seqno && R[0].seqno!= -1) {
/**** time to generate statistics ****/
// first, calculate mean time in batch
for (i=n=0, j=R[0].seqno, s=0.0; i<50; i++) {
if (R[i].seqno == j) {
n++;
s += R[i].Vclock;
}
else break;
}
mean = s / (double) n;
// then, get mean of difference from mean
for (i=0, j=R[0].seqno, s=0.0; i<50; i++) {
if (R[i].seqno == j)
s += (R[i].Vclock > mean) ?
(R[i].Vclock - mean) :
(mean - R[i].Vclock);
else break;
}
s /= (double) n;
// display result
if (n > 1) {
printf("t=%d.%03d ",T.tv_sec,T.tv_usec/1000);
printf("accuracy for count=%d is %d microsec ",j, (int) (s*1.0e6));
}
// also, show max
id1 = id2 = 0;
for (i=0, j=R[0].seqno, s=0.0; i<50; i++) {
if (R[i].seqno != j) break;
for (k=0; k<50; k++) {
if (R[k].seqno != j) break;
y = (R[k].Vclock > R[i].Vclock) ?
R[k].Vclock - R[i].Vclock :
R[i].Vclock - R[k].Vclock;
if (y>s) {
s = y;
id1 = R[i].id;
id2 = R[k].id;
}
}
}
if (n > 1) printf("max=%d n=%d ",(int) (s*1.0e6),n);
if (id1 != 0) printf("max apart are %d and %d\n",id1,id2);
else printf("\n");
// display skew values for the motes in the recorded array
for (i=n=0, j=R[0].seqno; i<50; i++) {
if (R[i].seqno!=j) break;
if (R[i].skew != 0.0) n++;
}
printf("t=%d.%03d ",T.tv_sec,T.tv_usec/1000);
printf("skews are:");
for (i=0, j=R[0].seqno; i<50; i++) {
if (R[i].seqno!=j) break;
if (R[i].skew != 0.0) printf(" %d(%e)",R[i].id,R[i].skew);
else printf(" %d(-)",R[i].id);
}
printf("\n");
// display calib values for the motes in the recorded array
for (i=n=0, j=R[0].seqno; i<50; i++) {
if (R[i].seqno!=j) break;
if (R[i].calibRatio != 0.0) n++;
}
printf("t=%d.%03d ",T.tv_sec,T.tv_usec/1000);
printf("calibration ratios are:");
for (i=0, j=R[0].seqno; i<50; i++) {
if (R[i].seqno!=j) break;
if (R[i].calibRatio != 0.0) printf(" %d(%e)",R[i].id,R[i].calibRatio);
else printf(" %d(-)",R[i].id);
}
printf("\n");
}
// add entry table, if possible
for (i=0; i<50; i++)
if (R[i].seqno != p->count) break;
if (i >= 50) return;
// found available entry, now record data
R[i].seqno = p->count;
R[i].id = p->sndId;
R[i].Vclock = V;
R[i].skew = p->skew;
R[i].calibRatio = p->calibRatio;
}
void displayBeac( beaconMsgPtr p ) {
struct timeval T;
double L,V,delay;
char lnib,rnib;
uint32_t w;
// show elapsed time since start of run
gettimeofday(&T,NULL);
T.tv_sec -= startT.tv_sec;
if (T.tv_usec >= startT.tv_usec) T.tv_usec -= startT.tv_usec;
else {
T.tv_sec--;
T.tv_usec += 1000000;
T.tv_usec -= startT.tv_usec;
}
printf("t=%d.%03d ",T.tv_sec,T.tv_usec/1000);
// show mode id, latest "diff" value
printf("id=%d ",p->sndId);
printf("diff=%d ",p->prevDiff);
// display local time in beacon message
L = (double) *(uint16_t *)p->Local;
L *= 4294967295.0 / (double) TPS;
L += (double) moteInt(&p->Local[2]) / (double) TPS;
// display virtual time in beacon message
V = (double) *(uint16_t *)p->Virtual;
V *= 4294967295.0 / (double) TPS;
V += (double) moteInt(&p->Virtual[2]) / (double) TPS;
// obtain MAC delay interval from beacon
delay = (double)nx_moteInt((uint8_t *)p->Delay) / (double) TPS;
// add delay to other times (adjusting properly)
L += delay;
V += delay;
// show times of beacon
printf(" Ltime=%f Vtime=%f delay=%f ",L,V,delay);
// print current mode, number of neighbors
lnib = (p->mode >> 4) & 0xf;
rnib = p->mode & 0xf;
lnib = (lnib > 9) ? 'A'+lnib-9 : '0' + lnib;
rnib = (rnib > 9) ? 'A'+rnib-9 : '0' + rnib;
printf("mode=%c%c ",lnib,rnib);
printf("nsize=%d\n",p->NbrSize);
}
void printHelp() {
printf("Syntax spy [-z|-t]\n");
printf("\t\t -z for a micaz mote and MIB serial forwarding\n");
printf("\t\t -t for a telos-type mote and USB serial forwarding\n");
}
int main(int argc, char **argv) {
int i,k,r;
int sock;
extern int errno;
extern int h_errno;
struct sockaddr_in toServer;
struct hostent * h;
struct pollfd waitor;
micaTOS_Msg bufferMica;
telosTOS_Msg bufferTelos;
uint8_t AMtype;
uint8_t AMlength;
uint8_t * dataP;
uint8_t x;
extern char *optarg;
extern int optind, opterr, optopt;
/** Parse arguments to set parameters **/
while (TRUE) {
k = getopt(argc, argv, "8tz");
if (k == -1) break;
switch ((char)k) {
case '8': motetype = MICA128; break;
case 'z': motetype = MICAZ; break;
case 't': motetype = TELOS; break;
case '?': printHelp(); exit(1);
}
}
if (motetype == 0) { printHelp(); exit(1); }
if (motetype == MICAZ) TPS = 921778;
if (motetype == TELOS) TPS = 1024*1024;
gettimeofday( &startT, NULL );
bzero((char *) &toServer, sizeof(toServer));
toServer.sin_family = AF_INET;
toServer.sin_port = htons(9001);
h = gethostbyname("localhost");
if (h == NULL) { perror("gethostbyname error"); exit(h_errno); }
bcopy(h->h_addr, (char *) &toServer.sin_addr, h->h_length);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) { perror("unable to create socket"); exit(errno); }
i = 1;
r = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof (i));
if (r < 0) { perror("setsockopt error");
close(sock); exit(errno); }
r = connect(sock, (struct sockaddr *) &toServer, sizeof(toServer));
if (r < 0) { perror("connect error"); exit(errno); }
// use the "poll()" function so that we don't get stuck
// trying to read from a socket that has no data
waitor.fd = sock;
waitor.events = POLLIN;
// do the silly "version exchange" that SFProtocol.java needs
exchange(sock);
/***** Loop to read any response(s) ********************/
while (TRUE) {
// here would be a chance to read from the keyboard someday ...
poll(&waitor,1,250);
if (!(waitor.revents & POLLIN)) continue; // no message!
if (motetype == TELOS) {
getStreamTelos(sock,&bufferTelos);
AMtype = bufferTelos.type;
AMlength = bufferTelos.length;
dataP = bufferTelos.data;
}
else {
getStreamMica(sock,&bufferMica);
AMtype = bufferMica.type;
AMlength = bufferMica.length;
dataP = bufferMica.data;
}
switch (AMtype) { // handle different AM msg types
case AM_BEACON: displayBeac((beaconMsgPtr) dataP); break;
case AM_PROBE_ACK:
displayProbeAck((beaconProbeAckPtr) dataP); break;
case AM_NEIGHBOR:
displayNeighbor((neighborMsgPtr) dataP); break;
case AM_UART:
displayBeac((beaconMsgPtr) dataP); break;
case AM_PROBE_DEBUG:
displayProbeDebug((beaconDebugMsgPtr) dataP); break;
case AM_NEIGHBOR_DEBUG:
displayNeighborDebug((beaconDebugMsgPtr) dataP); break;
case AM_SKEW:
displaySkew((skewMsgPtr) dataP); break;
default: break;
}
}
}
|
tinyos-io/tinyos-3.x-contrib | berkeley/acme/apps/ACMeterReactive/EnergyMsg.h | #ifndef ENERGYMSG_H_
#define ENERGYMSG_H_
#include <IeeeEui64.h>
enum {
AM_ENERGYMSG = 8,
};
typedef nx_struct EnergyMsg {
nx_uint16_t src;
nx_uint32_t energy;
nx_uint32_t laenergy;
nx_uint32_t lvaenergy;
nx_uint32_t lvarenergy;
nx_uint8_t eui64[IEEE_EUI64_LENGTH];
} EnergyMsg_t;
enum {
AM_SWITCHMSG = 9,
};
typedef nx_struct SwitchMsg {
nx_uint8_t nodeID;
nx_uint16_t toggle;
} SwitchMsg_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/compression/compressor.h | <filename>diku/common/tools/compression/compressor.h
/**************************************************************************
*
* compressor.h
*
* The platform specific parts needed by the compressors.
*
* This file is licensed under the GNU GPL.
*
* (C) 2005, <NAME> <<EMAIL>>
*
*/
#ifndef __MSP430__
#include <inttypes.h>
#endif
/*
* buffer is a pointer to nobytes of data
*/
void handle_full_buffer(uint8_t *buffer, uint16_t nobytes);
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/simulator/evaluator.h | <filename>eon/eon/src/simulator/evaluator.h<gh_stars>1-10
#ifndef EVALUATOR_H
#define EVALUATOR_H
#include "simulator.h"
#include <stdint.h>
#ifdef PLOAD
#include "omniloadpredictor.h"
#include "consumptionpredictor.h"
#else
#include "loadpredictor.h"
#include "consumptionpredictor.h"
#endif
#ifdef PENERGY
#include "omnienergypredictor.h"
#else
#ifdef EWMA
#include "ewmapredictor.h"
#else
#include "energypredictor.h"
#endif
#endif
using namespace std;
typedef struct
{
int energy_state;
double state_grade;
int64_t cost_of_reevaluation;
} energy_evaluation_struct_t;
#ifndef NUMTIMEFRAMES
#define NUMTIMEFRAMES 12
#endif
#ifdef STATIC_POLICY
int static_state = STATIC_STATE;
double static_grade = STATIC_GRADE;
#endif
uint16_t ENERGY_TIMESCALES[NUMTIMEFRAMES];
extern int64_t loss_per_unit_time;
extern int64_t battery_capacity;
int64_t perceived_battery = 0;
void init_evaluator()
{
int i;
printf("NUMTIMEFRAMES = %d\n",NUMTIMEFRAMES);
perceived_battery = battery_capacity/2;
ENERGY_TIMESCALES[0] = 1;
for (i=1; i < NUMTIMEFRAMES; i++)
{
ENERGY_TIMESCALES[i] = ENERGY_TIMESCALES[i-1]*2;
}
init_energy_predictor();
init_load_predictor();
printf("here\n");
init_consumption_predictor();
printf("init_evaluator done\n");
}
void eval_more_energy(int64_t energy, int64_t timestamp)
{
ep_more_energy(energy,timestamp);
}
void eval_increase_battery(int64_t energy){
char buf[512];
int64_t newfullness = perceived_battery + energy;
if (newfullness > battery_capacity)
{
newfullness = battery_capacity;
}
if (newfullness < 0){
newfullness= 0;
}
perceived_battery = newfullness;
}
void eval_path_done(int pathNum, int state, int64_t energy, int64_t timestamp)
{
cp_path_done(pathNum,state,energy);
lp_path_done(pathNum, timestamp);
}
int64_t predict_energy (vector<event_t*> *time_line,
int64_t current_index,
uint8_t timeframe, uint8_t state, double grade)
{
int64_t src_energy;
int64_t consumption;
int64_t load;
int64_t netenergy, idleloss;
if (state > NUMSTATES)
{
printf("ERROR: Invalid state!!! (s=%d)\n",state);
exit(2);
}
src_energy = predict_energy(time_line, current_index,
ENERGY_TIMESCALES[timeframe]);//predict source
load = lp_predict_load(time_line, current_index,
ENERGY_TIMESCALES[timeframe]);
consumption = cp_predict_consumption(ENERGY_TIMESCALES[timeframe],
load, state, grade);
idleloss = (ENERGY_TIMESCALES[timeframe] * (loss_per_unit_time * 60));
netenergy = src_energy - (consumption + idleloss);
//netenergy = src_energy-consumption;
printf("predict_energy(%lld, %d, %d, %lf)->(%lld,%lld,%lld,%lld)\n",
current_index,timeframe,state,grade,src_energy,load,consumption, idleloss);
return netenergy;
}
bool predict_state (vector<event_t*> *time_line,
int64_t thebattery, int64_t current_index,
uint8_t state, double grade, int64_t *energy_result)
{
int timeframe = 0;
uint64_t waste_energy = 0;
int64_t netenergy, newbattery = 0;
int64_t immediate_waste = 0;
bool dead = FALSE;
int64_t battery;
#ifdef PERFECT_BATTERY
battery = thebattery;
#else
battery = perceived_battery;
#endif
while (timeframe < NUMTIMEFRAMES && !dead)
{
dead = TRUE;
netenergy = predict_energy(time_line, current_index, timeframe, state, grade);
newbattery = battery + netenergy - waste_energy;
if (energy_result != NULL)
{
*energy_result = newbattery;
}
if (newbattery <= (int64_t)battery_capacity)
{
immediate_waste = 0;
} else {
immediate_waste = newbattery - battery_capacity;
newbattery = battery_capacity;
}
#ifdef ACCUM_WASTE
waste_energy += immediate_waste;
#else
waste_energy = 0;
#endif
printf("t=%d---s=%d --> ",timeframe, state);
printf("(%lld,%lld,%lld,%lld)\n",battery, netenergy, waste_energy, immediate_waste);
if (newbattery <= 0)
{
dead = TRUE;
printf("DEAD!\n");
} else {
dead = FALSE;
printf("Not Dead\n");
}
if (!dead)
{
timeframe++;
}
}
return !dead;
}
energy_evaluation_struct_t *reevaluate_energy_level(
vector<event_t*>* time_line,
int current_index,
int64_t battery_state)
{
energy_evaluation_struct_t * ret = new energy_evaluation_struct_t;
#ifdef CONSERVE
ret->state_grade = 0.0;
ret->energy_state = STATE_BASE;
ret->cost_of_reevaluation = 0;
return ret;
#endif
#ifdef SPEND
ret->state_grade = 1.0;
ret->energy_state = 0;
ret->cost_of_reevaluation = 0;
return ret;
#endif
#ifdef STATIC_POLICY
ret->energy_state = static_state;
ret->state_grade = static_grade;
ret->cost_of_reevaluation = 0;
return ret;
#endif
uint8_t state = 0; //set to max state
bool minalive = FALSE;
bool maxalive;
int64_t minenergy = 0;
int64_t maxenergy = 0;
while (state <= STATE_BASE && !minalive)
{
minalive = predict_state(time_line, battery_state, current_index, state, 0.0, &minenergy);
if (!minalive)
{
state++;
}
}
//we have the right state...now get the grade
if (!minalive)
{
state = STATE_BASE;
ret->state_grade = 0.0;
} else {
maxalive = predict_state(time_line, battery_state, current_index, state, 1.0, &maxenergy);
if (maxalive)
{
ret->state_grade = 1.0;
} else {
#ifdef BROKENGRADE
int64_t rightenergy = (-1) * (battery_state);
int64_t nume = (minenergy);
int64_t den = (minenergy-maxenergy);
double dn = (double)nume;
double dd = (double)den;
//since the energy is not linear, this will
//significantly under-predict
ret->state_grade = dn/dd;
//printf("re=%lld,min=%lld,max=%lld,dn=%lf,dd=%lf\n",rightenergy,minenergy,maxenergy,dn,dd);
#else
double mingrade = 0.0;
double maxgrade = 1.0;
double midgrade;
while ((maxgrade - mingrade) > .001)
{
midgrade = (mingrade + maxgrade)/2;
if (predict_state(time_line, battery_state, current_index, state, midgrade,NULL))
{
mingrade = midgrade;
} else {
maxgrade = midgrade;
}
}
ret->state_grade = midgrade;
#endif //BROKENGRADE
}
}
ret->energy_state = state;
ret->cost_of_reevaluation = 0;
printf("state = %d(%lf)\n",state, ret->state_grade);
return ret;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/tinyos2/SrcAccum.h | <reponame>tinyos-io/tinyos-3.x-contrib<filename>eon/eon/src/runtime/tinyos2/SrcAccum.h
#ifndef SRCACCUM_H
#define SRCACCUM_H
#define BIN_MS 1024L
#define POLL_2770_INTERVAL (3L * 1024L)
#define POLL_2751_INTERVAL (256L)
#define POLL_DIFF_FACTOR (POLL_2770_INTERVAL / POLL_2751_INTERVAL)
#define POLL_CYCLES 1
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/error.h | #ifndef __ERROR_H__
#define __ERROR_H__
/* Connection timed out */
#define ETIMEDOUT 116
typedef enum {
USB_ERROR_TYPE_NONE = 0,
USB_ERROR_TYPE_STRING,
USB_ERROR_TYPE_ERRNO,
} usb_error_type_t;
void usb_error(char *format, ...);
void usb_message(char *format, ...);
const char *usb_win_error_to_string(void);
int usb_win_error_to_errno(void);
#endif /* _ERROR_H_ */
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/linuxsim/simworld/testsw.c | #include "simworld.h"
//#include <pthread.h>
void energy_cb(int uJin, int uJout, unsigned int uJbatt)
{
log_output(ACTION_USER,"%d,%d,%u",uJin, uJout, uJbatt);
}
void * recv_thread(void *arg)
{
while(1)
{
int to, val;
val = recv_network_int(0, &to);
//sim_sleep(10);
if (!to)
{
send_network_int(val);
}
}
}
void *hello(void *arg)
{
int i;
printf("Hello! I'm a thread!\n");
while(1)
{
get_sensor_reading();
sim_sleep(5000);
}
return NULL;
}
int main(int argc, char **argv)
{
int rc, t;
pthread_t pt, rt;
int self = pthread_self();
printf("main self=%d\n", self);
set_energy_callback(energy_cb);
rc = sim_pthread_create(&pt, NULL, hello, NULL);
if (rc)
{
printf("pthread_create: FAILED\n");
exit(-1);
}
rc = sim_pthread_create(&rt, NULL, recv_thread, NULL);
//pthread_join(pt, NULL);
while (1)
{
sim_sleep(50);
}
}
|
tinyos-io/tinyos-3.x-contrib | eon/apps/server-e/impl/stargate/userstructs.h | #ifndef USER_STRUCTS_H_INCLUDED
#define USER_STRUCTS_H_INCLUDED
#include "ServerE.h"
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/support/sdk/c/blip/interface/config.c | <gh_stars>1-10
/*
* "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."
*
*/
/*
* @author <NAME> <<EMAIL>>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <lib6lowpan/ip.h>
#include "device-config.h"
#include "logging.h"
#define BUF_LEN 200
struct config *lastconfig;
void rm_comment (char *buf) {
while (*buf != '#' && *buf != '\0')
buf++;
*buf = '\0';
}
void upd_start(char **buf) {
while ((**buf == ' ' || **buf == '\t' || **buf == '\n') && **buf != '\0')
*buf = (*buf) + 1;
}
int config_parse(const char *file, struct config *c) {
char *buf, real_buf[BUF_LEN], arg[BUF_LEN];
FILE *fp = fopen(file, "r");
int gotargs = 0;
if (fp == NULL) return 1;
// defaults
c->retries = 3; // BLIP_L2_RETRIES;
c->lpl_interval = 0;
c->delay = 30;
c->panid = 0x22;
while (fgets(real_buf, BUF_LEN, fp) != NULL) {
buf = real_buf;
rm_comment(buf);
upd_start(&buf);
if (sscanf(buf, "prefix %s\n", arg) > 0) {
inet_pton6(arg, &c->router_addr);
gotargs ++;
} else if (sscanf(buf, "channel %i\n", &c->channel) > 0) {
if (c->channel < 11 || c->channel > 26) {
fatal("Invalid channel specified in '%s'\n", file);
exit(1);
}
gotargs ++;
} else if (sscanf(buf, "log %s\n", arg) > 0) {
int i;
for (i = 0; i < 5; i++) {
if (strncmp(log_names[i], arg, strlen(log_names[i])) == 0) {
info("Read log level: %s\n", arg);
log_setlevel(i);
break;
}
}
} else if (sscanf(buf, "retry %i\n", &c->retries) > 0) {
if (c->retries <= 0 || c->retries > 25) {
warn("retry value set to %i: outside of the recommended range (0,25]\n", c->retries);
}
} else if (sscanf(buf, "lpl %i\n", &c->lpl_interval) > 0) {
debug("LPL interval set to %i\n", c->lpl_interval);
} else if (sscanf(buf, "delay %i\n", &c->delay) > 0) {
debug("Radio delay set to %ims\n", c->delay);
} else if (*buf != '\0') {
// anything else indicates that there's invalid input.
return 1;
}
}
fclose(fp);
if (gotargs < 2) return 1;
info("Read config from '%s'\r\n", file);
info("Using channel %i\r\n", c->channel);
debug("Retries: %i\r\n", c->retries);
lastconfig = c;
return 0;
}
#if 0
#define STR(X) #X
void config_print(int fd, int argc, char **argv) { //struct config *c) {
VTY_HEAD;
char buf[64];
VTY_printf ("configuration:\r\n");
inet_ntop(AF_INET6, &lastconfig->router_addr, buf, 64);
VTY_printf(" router address: %s\r\n", buf);
VTY_printf(" proxy dev: %s\r\n", lastconfig->proxy_dev);
VTY_printf(" version: %s\r\n", " $Id: config.c,v 1.2 2009/08/09 23:36:05 sdhsdh Exp ");
VTY_printf(" radio retries: %i delay: %ims channel: %i lpl interval: %ims \r\n",
lastconfig->retries, lastconfig->delay, lastconfig->channel, lastconfig->lpl_interval);
VTY_flush();
}
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/support/sdk/c/blip/lib6lowpan/utility.c |
#include <stdint.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "lib6lowpan-includes.h"
#include "lib6lowpan.h"
#include "ip.h"
#define TO_CHAR(X) (((X) < 10) ? ('0' + (X)) : ('a' + ((X) - 10)))
#define CHAR_VAL(X) (((X) >= '0' && (X) <= '9') ? ((X) - '0') : \
(((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : ((X) - 'a' + 10)))
void inet_pton6(char *addr, struct in6_addr *dest) {
uint16_t cur = 0;
char *p = addr;
uint8_t block = 0, shift = 0;
if (addr == NULL || dest == NULL) return;
memset(dest->s6_addr, 0, 16);
// first fill in from the front
while (*p != '\0') {
if (*p != ':') {
cur <<= 4;
cur |= CHAR_VAL(*p);
} else {
dest->s6_addr16[block++] = htons(cur);
cur = 0;
}
p++;
if (*p == '\0') {
dest->s6_addr16[block++] = htons(cur);
return;
}
if (*(p - 1) == ':' && *p == ':') {
break;
}
}
// we must have hit a "::" which means we need to start filling in from the end.
block = 7;
cur = 0;
while (*p != '\0') p++;
p--;
// now pointing at the end of the address string
while (p > addr) {
if (*p != ':') {
cur |= (CHAR_VAL(*p) << shift);
shift += 4;
} else {
dest->s6_addr16[block--] = htons(cur);
cur = 0; shift = 0;
}
p --;
if (*(p + 1) == ':' && *p == ':') break;
}
}
int inet_ntop6(struct in6_addr *addr, char *buf, int cnt) {
uint16_t block;
char *end = buf + cnt;
int i, j, compressed = 0;
for (j = 0; j < 8; j++) {
if (buf > end - 7) return -1;
block = ntohs(addr->s6_addr16[j]);
for (i = 4; i <= 16; i+=4) {
if (block > (0xffff >> i) || (compressed == 2 && i == 16)) {
*buf++ = TO_CHAR((block >> (16 - i)) & 0xf);
}
}
if (addr->s6_addr16[j] == 0 && compressed == 0) {
*buf++ = ':';
compressed++;
}
if (addr->s6_addr16[j] != 0 && compressed == 1) compressed++;
if (j < 7 && compressed != 1) *buf++ = ':';
}
*buf++ = '\0';
return buf - (end - cnt);
}
uint16_t ieee154_hashaddr(ieee154_addr_t *addr) {
if (addr->ieee_mode == IEEE154_ADDR_SHORT) {
return addr->i_saddr;
} else if (addr->ieee_mode == IEEE154_ADDR_EXT) {
uint16_t i, hash = 0, *current = (uint16_t *)addr->i_laddr.data;
for (i = 0; i < 4; i++)
hash += *current ++;
return hash;
} else {
return 0;
}
}
#ifndef PC
uint32_t ntohl(uint32_t i) {
uint16_t lo = (uint16_t)i;
uint16_t hi = (uint16_t)(i >> 16);
lo = (lo << 8) | (lo >> 8);
hi = (hi << 8) | (hi >> 8);
return (((uint32_t)lo) << 16) | ((uint32_t)hi);
}
uint8_t *ip_memcpy(uint8_t *dst0, const uint8_t *src0, uint16_t len) {
uint8_t *dst = (uint8_t *) dst0;
uint8_t *src = (uint8_t *) src0;
uint8_t *ret = dst0;
for (; len > 0; len--)
*dst++ = *src++;
return ret;
}
#endif
#ifdef PC
char *strip(char *buf) {
char *rv;
while (isspace(*buf))
buf++;
rv = buf;
buf += strlen(buf) - 1;
while (isspace(*buf)) {
*buf = '\0';
buf--;
}
return rv;
}
int ieee154_parse(char *in, ieee154_addr_t *out) {
int i;
long val;
char *endp = in;
long saddr = strtol(in, &endp, 16);
printf("ieee154_parse: %s, %c\n", in, *endp);
if (*endp == ':') {
endp = in;
// must be a long address
for (i = 0; i < 8; i++) {
val = strtol(endp, &endp, 16);
out->i_laddr.data[i] = val;
endp++;
}
out->ieee_mode = IEEE154_ADDR_EXT;
} else {
out->i_saddr = htole16(saddr);
out->ieee_mode = IEEE154_ADDR_SHORT;
}
return 0;
}
int ieee154_print(ieee154_addr_t *in, char *out, size_t cnt) {
int i;
char *cur = out;
switch (in->ieee_mode) {
case IEEE154_ADDR_SHORT:
snprintf(out, cnt, "IEEE154_ADDR_SHORT: 0x%x", in->i_saddr);
break;
case IEEE154_ADDR_EXT:
cur += snprintf(out, cnt, "IEEE154_ADDR_EXT: ");
for (i = 0; i < 8; i++) {
cur += snprintf(cur, cnt - (cur - out), "%02x", in->i_laddr.data[i]);
if (i < 7)
*cur++ = ':';
}
break;
}
return 0;
}
void print_buffer(uint8_t *buf, int len) {
int i;
for (i = 0; i < len; i++) {
if ((i % 16) == 0 && i > 0)
printf("\n");
if (i % 16 == 0) {
printf("%i:\t", i);
}
printf("%02x ", buf[i]);
}
printf("\n");
}
void scribble(uint8_t *buf, int len) {
int i;
for (i = 0; i < len; i++) {
buf[i] = rand();
}
}
void iov_print(struct ip_iovec *iov) {
struct ip_iovec *cur = iov;
while (cur != NULL) {
int i;
printf("iovec (%p, %i) ", cur, cur->iov_len);
for (i = 0; i < cur->iov_len; i++) {
printf("%02hhx ", cur->iov_base[i]);
}
printf("\n");
cur = cur->iov_next;
}
}
#endif
|
tinyos-io/tinyos-3.x-contrib | rincon/apps/BlackbookBridge/BFileReadBridge/BFileRead.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
*/
/**
* Automatically generated header file for BFileRead
*/
#ifndef BFILEREAD_H
#define BFILEREAD_H
#include "message.h"
#define BFILEREAD_BYTE_ARRAY_LENGTH (TOSH_DATA_LENGTH-9)
typedef nx_struct BFileReadMsg {
nx_uint8_t bool0;
nx_uint8_t short0;
nx_uint8_t short1;
nx_uint16_t int0;
nx_uint32_t long0;
nx_uint8_t byteArray[BFILEREAD_BYTE_ARRAY_LENGTH];
} BFileReadMsg;
enum {
CMD_OPEN = 0,
REPLY_OPEN = 1,
CMD_ISOPEN = 2,
REPLY_ISOPEN = 3,
CMD_CLOSE = 4,
REPLY_CLOSE = 5,
CMD_READ = 6,
REPLY_READ = 7,
CMD_SEEK = 8,
REPLY_SEEK = 9,
CMD_SKIP = 10,
REPLY_SKIP = 11,
CMD_GETREMAINING = 12,
REPLY_GETREMAINING = 13,
EVENT_OPENED = 14,
EVENT_CLOSED = 15,
EVENT_READDONE = 16,
};
enum {
AM_BFILEREADMSG = 0xB5,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/telos/fluxhandler.h | <gh_stars>1-10
#ifndef FLUXHANDLER_H_INCLUDED
#define FLUXHANDLER_H_INCLUDED
#include "../marshaller.h"
#include "rt_structs.h"
bool isReadyByID (EdgeIn * edge);
result_t callEdge (EdgeIn * e);
result_t callError (uint16_t nodeid, Handle in, uint8_t error);
uint16_t getErrorWeight (uint16_t nodeid);
//void factorSGDC (uint8_t state, bool awake);
bool islocal (uint16_t nodeid);
bool doremoteenqueue (EdgeQueue * q, EdgeIn edge);
task void RemoteConsumerTask ();
task void SleepTask();
//global variables
uint8_t gStargateLoad=0;
enum {
ASLEEP =0,
SLEEPY =1,
AWAKE =3,
WAKING =4,
};
int remoteCstate = ASLEEP;
/*void
factorTime (uint16_t nodeid, uint32_t start, uint32_t end)
{
uint32_t elapsed;
double d_elapsed_ms;
if (start > end)
return;
if (start == end)
{
elapsed = 1; //round up to 1us
}
else
{
elapsed = end - start;
}
d_elapsed_ms = ((double) elapsed) / 1000.0;
atomic
{
nodeTimeMS[nodeid] =
(nodeTimeMS[nodeid] * (PATHRATEHISTORY - 1.0) +
d_elapsed_ms) / ((double) PATHRATEHISTORY);
}
}
void
factorWakeTime (uint32_t start, uint32_t end)
{
uint32_t elapsed;
double d_elapsed_ms;
if (start > end)
return;
if (start == end)
{
elapsed = 1; //round up to 1us
}
else
{
elapsed = end - start;
}
d_elapsed_ms = ((double) elapsed) / 1000.0;
wakeTimeMS =
(wakeTimeMS * (PATHRATEHISTORY - 1.0) +
d_elapsed_ms) / ((double) PATHRATEHISTORY);
}
void
factorWeight (uint16_t pathweight)
{
pathRate[pathweight]++;
}
void factorWake (uint16_t path, bool wake)
{
double val;
if (wake)
{
val = 1.0;
}
else
{
val = 0.0;
}
wakeupProb[path] =
(wakeupProb[path] * (WAKEUPPROBHISTORY - 1.0) +
val) / ((double) WAKEUPPROBHISTORY);
}
void factorSGDC (uint8_t state, bool awake)
{
double val;
if (awake)
{
val = 1.0;
}
else
{
val = 0.0;
}
stargateDutyCycle[state] =
stargateDutyCycle[state] + (val -
stargateDutyCycle[state]) / ((double) SGDCHISTORY);
}
*/
/************************************
* Stargate Wakeup events
*
*
************************************/
event result_t SGWakeup.wakeDone ()
{
uint32_t wakeEnd;
gStargateLoad = 0;
wakeEnd = call LocalTime.read ();
wakeWaiting = FALSE;
//factorWakeTime (wakeStart, wakeEnd);
remoteCstate = AWAKE;
if (post RemoteConsumerTask() == TRUE)
{
}
return SUCCESS;
}
event result_t SGWakeup.sleepDone (result_t success)
{
static int count = 0;
wakeWaiting = FALSE;
if (success == FAIL)
{
count++;
if (count < 10)
{
post SleepTask();
}
} else {
count = 0;
}
atomic
{
if (!isqueueempty (&remoteQ))
{
remoteCstate = WAKING;
post RemoteConsumerTask();
} else {
remoteCstate = ASLEEP;
}
}
return SUCCESS;
}
/************************************
*
* EDGE Consumer/Producer functions
*
************************************/
task void
LocalConsumerTask ()
{
uint16_t result;
uint16_t delay, ready;
EdgeIn edge;
delay = FALSE;
result = dequeue (&moteQ, &edge);
if (result == TRUE)
{
//Got an edge
//is it ready
ready = isReadyByID (&edge);
if (!islocal (edge.node_id))
{
doremoteenqueue (&remoteQ, edge);
} else {
if (!ready)
{
//not ready, put it to the back of the queue
enqueue (&moteQ, edge);
delay = TRUE;
} else {
result = callEdge(&edge);
} //if
} //if islocal
}
atomic
{
if (isqueueempty (&moteQ))
{
localCAlive = FALSE;
}
}//atomic
if (localCAlive == TRUE)
{
if (delay == TRUE)
{
//delay execution a little bit
call localQTimer.start (TIMER_ONE_SHOT, QUEUE_DELAY);
}
else
{
post LocalConsumerTask ();
} //else(delay)
}//else(still alive)
} //end LocalConsumerTask
event result_t localQTimer.fired ()
{
if (!post LocalConsumerTask ())
{
call localQTimer.start (TIMER_ONE_SHOT, QUEUE_DELAY);
}
return SUCCESS;
}
task void RemoteConsumerTask ()
{
bool result, delay;
uint8_t marshall_result;
static EdgeIn edge;
uint16_t connid;
static bool marshalling = FALSE;
static int marshall_count = 0;
delay = FALSE;
// if (!call SGWakeup.isawake ())
if (remoteCstate == WAKING)
{
wakeStart = call LocalTime.read ();
wakeWaiting = TRUE;
result = call SGWakeup.wake (); //wake up and wait
if (result == FAIL)
{
wakeWaiting = FALSE;
delay = TRUE;
} else {
return;
}
}
if (remoteCstate == AWAKE) {
if (marshalling)
{
call SGWakeup.getConnection(&connid);
//try to marshall the edge
marshall_result = encodeEdge (connid, edge, marshall_count);
if (marshall_result == MARSH_OK)
{
marshall_count++;
}
else if (marshall_result == MARSH_DONE)
{
//free memory
call BAlloc.free ((Handle) edge.invar);
//call BAlloc.free ((Handle) edge.outvar);
marshalling = FALSE;
marshall_count = 0;
delay = TRUE;
}
else if (marshall_result == MARSH_FULL)
{
delay = TRUE;
}
else
{
//marshalling error. Not good at all.
marshalling = FALSE;
marshall_count = 0;
delay = TRUE;
}
}
else
{
result = dequeue (&remoteQ, &edge);
if (result == TRUE)
{
//Got an edge, Stargate Bound
marshalling = TRUE;
marshall_count = 0;
call Leds.redToggle();
call SGWakeup.upLoad();
call SleepTimer.stop ();
//set up for marshalling
} //if got edge
} //else marshalling
}//state AWAKE
if (remoteCstate == AWAKE)
{
if (delay == TRUE)
{
//delay execution a little bit
call remoteQTimer.start (TIMER_ONE_SHOT, QUEUE_DELAY * 100);
}
else
{
post RemoteConsumerTask ();
}//else(delay)
}
}
event result_t SGWakeup.pathDone(uint16_t path, uint32_t elapsed)
{
if (call SGWakeup.getLoad() == 0)
{
call Leds.yellowToggle();
call SleepTimer.start (TIMER_ONE_SHOT, 2 * 1024);
}
//insert path accounting stuff here
return SUCCESS;
}
task void SleepTask()
{
result_t res;
static int count = 0;
res = call SGWakeup.sleep();
if (!res)
{
count++;
if (count < 4)
{
post SleepTask();
}
} else {
count = 0;
remoteCAlive = FALSE;
}
}
event result_t SleepTimer.fired ()
{
call Leds.greenToggle();
if (remoteCstate == AWAKE && call SGWakeup.getLoad() == 0)
{
remoteCstate = SLEEPY;
post SleepTask();
}
return SUCCESS;
}
event result_t remoteQTimer.fired ()
{
if (remoteCstate == AWAKE)
{
return SUCCESS;
}
if (!post RemoteConsumerTask ())
{
call remoteQTimer.start (TIMER_ONE_SHOT, QUEUE_DELAY * 100);
}
return SUCCESS;
}
bool
isFunctionalState (uint8_t state)
{
return TRUE;
}
/*********************************
* A wrapper for enqueue to manage
* the posting of consumer tasks
********************************/
bool
dolocalenqueue (EdgeQueue * q, EdgeIn edge)
{
bool result;
atomic
{
result = enqueue (q, edge);
if (result && localCAlive == FALSE)
{
localCAlive = TRUE;
post LocalConsumerTask ();
}
} //atomic
return result;
}
/*********************************
* A wrapper for enqueue to manage
* the posting of consumer tasks
********************************/
bool
doremoteenqueue (EdgeQueue * q, EdgeIn edge)
{
bool result;
atomic
{
result = enqueue (q, edge);
atomic {
if (result && remoteCstate == ASLEEP)
{
remoteCstate = WAKING;
post RemoteConsumerTask ();
}
}
} //atomic
return result;
}
/********************************
* AUX functions
********************************/
uint16_t
getNextSession ()
{
uint16_t nextid;
atomic
{
nextid = session_id;
session_id++;
}
return nextid;
}
result_t
handle_exit (Handle data)
{
GenericNode **ndata = (GenericNode **) data;
//factorWeight ((*ndata)->_pdata.weight);
//factorWake ((*ndata)->_pdata.weight, (*ndata)->_pdata.wake);
call BAlloc.free (data);
return SUCCESS;
}
result_t
handle_error (uint16_t nodeid, Handle indata, uint8_t error)
{
//add weight
GenericNode **ndata = (GenericNode **) indata;
(*ndata)->_pdata.weight += getErrorWeight (nodeid);
if (error == ERR_NOMEMORY)
{
}
if (error == ERR_QUEUE)
{
}
//call the correct error handler
return callError (nodeid, indata, error);
}
//CODE FOR HANDLING EDGES BETWEEN NODES
result_t
handle_edge (uint16_t nodeid,
Handle outdata, bool local, uint16_t edgewt)
{
result_t result;
Handle hin;
Handle hout;
EdgeIn newedge;
//out becomes in.
hin = outdata;
//needs to be done right before calling nodeCall;
/*
//allocate next out variable
result = call BAlloc.allocate (&hout, newoutsize);
if (result == FAIL)
{
call BAlloc.free (hout);
//error handling code
return handle_error (nodeid, hin, ERR_NOMEMORY);
}
*/
//put it on the queue
//Copy src contents to new edge
((GenericNode *) (*hin))->_pdata.weight += edgewt;
/*
((GenericNode *) (*hout))->_pdata.sessionID =
((GenericNode *) (*hin))->_pdata.sessionID;
((GenericNode *) (*hout))->_pdata.weight =
((GenericNode *) (*hin))->_pdata.weight;
*/
newedge.node_id = nodeid;
newedge.invar = (uint8_t **) hin;
//newedge.outvar = (uint8_t **) hout;
if (local)
{
if (!dolocalenqueue (&moteQ, newedge))
{
//queue is full
return handle_error (nodeid, hin, ERR_QUEUE);
}
}
else
{
if (!doremoteenqueue (&remoteQ, newedge))
{
//queue is full
return handle_error (nodeid, hin, ERR_QUEUE);
}
}
return SUCCESS;
}
//CODE FOR HANDLING EDGES BETWEEN NODES
result_t
handle_src_edge (uint16_t nodeid,
Handle outdata,
uint16_t session, bool local, uint16_t edgewt)
{
result_t result;
Handle hin;
Handle hout;
EdgeIn newedge;
uint16_t datasize;
//allocate in variable
datasize = call BAlloc.size (outdata);
result = call BAlloc.allocate (&hin, datasize);
if (result == FAIL)
{
//error handling code
return handle_error (nodeid, outdata, ERR_NOMEMORY);
}
memcpy (*hin, *outdata, datasize);
/*
//allocate next out variable
result = call BAlloc.allocate (&hout, newoutsize);
if (result == FAIL)
{
call BAlloc.free (hout);
//error handling code
return handle_error (nodeid, outdata, ERR_NOMEMORY);
}
*/
//put it on the queue
//Copy src contents to new edge
((GenericNode *) (*hin))->_pdata.sessionID = session;
((GenericNode *) (*hin))->_pdata.sessionID = session;
((GenericNode *) (*hin))->_pdata.weight = edgewt;
((GenericNode *) (*hin))->_pdata.minstate = STATE_BASE;
((GenericNode *) (*hin))->_pdata.wake = FALSE;
newedge.node_id = nodeid;
newedge.invar = (uint8_t **) hin;
//newedge.outvar = (uint8_t **) hout;
if (local)
{
if (!dolocalenqueue (&moteQ, newedge))
{
//queue is full
return handle_error (nodeid, hin, ERR_QUEUE);
}
}
else
{
if (!doremoteenqueue (&remoteQ, newedge))
{
//queue is full
return handle_error (nodeid, hin, ERR_QUEUE);
}
}
return SUCCESS;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | csau/misc/apps/tests/LplTest/src/LplTest.h | <filename>csau/misc/apps/tests/LplTest/src/LplTest.h
#ifndef LPLTEST_H
#define LPLTEST_H
#include "message.h"
#include "AM.h"
enum {
AM_LPLTEST_MSG = 10,
};
typedef nx_struct lpltest_msg {
nx_uint32_t seqno;
nx_uint8_t values[TOSH_DATA_LENGTH-sizeof(nx_uint32_t)];
} lpltest_msg_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | cedt/tos/chips/atm128/sim/atm128current.h | <gh_stars>1-10
/**
* "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 ATMEGA128POWER_H
#define ATMEGA128POWER_H
//used for energy computation of the MCU
#define MCU_POWER_IDLE_CURRENT 0.0033 //3.3 mA
#define MCU_POWER_ADC_NR_CURRENT 0.001 //1 mA
#define MCU_POWER_EXT_STANDBY_CURRENT 0.000243 //243 uA
#define MCU_POWER_SAVE_CURRENT 0.000124 //124 uA
#define MCU_POWER_STANDBY_CURRENT 0.000237 //237 uA
#define MCU_POWER_DOWN_CURRENT 0.000116 //116 uA
#define MCU_POWER_ON_CURRENT 1 // 0.0076 //7.6 mA
//predefine the voltage to a average value (3 + 2.5)/2
#define VOLTAGE 3
//other peripheral
#define LED_CURRENT 0.0022
#endif
|
tinyos-io/tinyos-3.x-contrib | blaze/tos/chips/ccxx00_single/Fcf.h | /*
* Copyright (c) 2005-2006 Arch Rock 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 Arch Rock 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>
* @author <NAME>
*/
#ifndef FCF_H
#define FCF_H
/**
* FCF 2006
* bits: 0-1 2 3 4 5 6 7 8-9 10-11 12-13 14-15
* Frame Type sFCF=0 Security Frame Pending ACK request PANId Compression Reserved Reserved Dest. Addressing Mode Frame Version Source Addressing Mode
*/
/**
* sFCF
* bits: 0-1 2 3 4 5 6 7
* Frame Type sFCF=1 Security Frame Pending ACK request Reserved Reserved
*/
typedef struct fcf_t {
uint8_t frameType : 2;
bool sFcf : 1;
bool security : 1;
bool framePending : 1;
bool ackRequest : 1;
bool panIdCompression : 1;
bool reserved0 : 1;
uint8_t reserved1 : 2;
uint8_t destAddressMode : 2;
uint8_t frameVersion : 2;
uint8_t srcAddressMode : 2;
} fcf_t;
typedef struct sfcf_t {
uint8_t frameType : 2;
bool sFcf : 1;
bool security : 1;
bool framePending : 1;
bool ackRequest : 1;
bool reserved : 1;
bool frameVersion : 1;
} sfcf_t;
/**
* This defines the bit-fields of our CCxx00 FCF byte
*/
enum fcf_enums {
FCF_FRAME_TYPE = 0,
FCF_SECURITY_ENABLED = 2,
FCF_FRAME_PENDING = 3,
FCF_ACK_REQ = 4,
};
enum frame_type_enums {
FRAME_TYPE_DATA = 0,
FRAME_TYPE_ACK = 1,
};
enum iee154_fcf_addr_mode_enums {
IEEE154_ADDR_NONE = 0,
IEEE154_ADDR_SHORT = 2,
IEEE154_ADDR_EXT = 3,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/daq/kernel-driver/ixpci_kernel.h | /* Declarations for PCI DAQ series.
Author: <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, 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. */
/* File level history (record changes for this file here.)
v 0.10.0 25 Jun 2003 by <NAME>
Defines IXPCI_PROC_FILE.
v 0.9.0 11 Mar 2003 by <NAME>
Gives support to PCI-TMC12.
Gives sub-vendor and sub-device IDs.
v 0.8.0 9 Jan 2003 by <NAME>
PCI-1002.
v 0.7.0 9 Jan 2003 by <NAME>
Gives support to PCI-P8R8.
v 0.6.0 7 Jan 2003 by <NAME>
Gives support to PCI-1002.
Adds base address ranges for ixpci_devinfo.
v 0.5.0 11 Nov 2002 by <NAME>
ICPDAS_LICENSE
Removes some unused symbols.
v 0.4.2 11 Sep 2002 by <NAME>
Adds symbol void *(_cardname) (int,int)
v 0.4.1 26 Jul 2002 by <NAME>
Just refines some codes.
v 0.4.0 16 May 2002 by <NAME>
Gives support to PCI-P16R16/P16C16/P16POR16
v 0.3.0 1 Nov 2001 by <NAME>
Macros for Kernel 2.2 compatibility
cleanup_module()
init_module()
v 0.2.0 31 Oct 2001 by <NAME>
Macros for Kernel 2.2 compatibility
module_register_chrdev()
module_unregister_chrdev()
v 0.1.0 25 Oct 2001 by <NAME>
Re-filenames to ixpci.h (from pdaq.h.)
Changes all "pdaq" to "ixpci."
v 0.0.0 10 Apr 2001 by <NAME>
Create. */
#ifndef _IXPCI_KERNEL_H
#define _IXPCI_KERNEL_H
#include "ixpci.h"
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/version.h>
#define ICPDAS_LICENSE "GPL"
/* General Definition */
#define ORGANIZATION "icpdas"
#define FAMILY "ixpci" /* name of family */
#define DEVICE_NAME "ixpci" /* device name used in /dev and /proc */
#define DEVICE_NAME_LEN 5
#define DEVICE_MAJOR 0 /* dynamic allocation of major number */
#define PBAN PCI_BASE_ADDRESSES_NUMBER
#define CNL CARD_NAME_LENGTH
#define KMSG(fmt, args...) printk(KERN_INFO FAMILY ": " fmt, ## args)
/* PCI Card's ID (vendor id).(device id) */
/*
0x 1234 5678 1234 5678
---- ---- ---- ----
| | | |
vendor id | | sub-device id
device id sub-vendor id
*/
#define PCI_1800 0x1234567800000000ULL /* conflict */
#define PCI_1802 0x1234567800000000ULL /* conflict */
#define PCI_1602 0x1234567800000000ULL /* conflict */
#define PCI_1602_A 0x1234567600000000ULL
#define PCI_1202 0x1234567200000000ULL
#define PCI_1002 0x12341002c1a20823ULL
#define PCI_P16C16 0x12341616c1a20823ULL /* conflict */
#define PCI_P16R16 0x12341616c1a20823ULL /* conflict */
#define PCI_P16POR16 0x12341616c1a20823ULL /* conflict */
#define PCI_P8R8 0x12340808c1a20823ULL
#define PCI_TMC12 0x10b5905021299912ULL
#define PCI_M512 0x10b5905021290512ULL
#define PCI_M256 0x10b5905021290256ULL
#define PCI_M128 0x10b5905021290128ULL
#define PCI_9050EVM 0x10b5905010b59050ULL
#define IXPCI_VENDOR(a) ((a) >> 48)
#define IXPCI_DEVICE(a) (((a) >> 32) & 0x0ffff)
#define IXPCI_SUBVENDOR(a) (((a) >> 16) & 0x0ffff)
#define IXPCI_SUBDEVICE(a) ((a) & 0x0ffff)
/* IXPCI cards' definition */
struct ixpci_carddef {
__u64 id; /* composed sub-ids */
unsigned int present; /* card's present counter */
char *module; /* module name, if card is present then
load module in this name */
char *name; /* card's name */
};
extern struct ixpci_carddef ixpci_card[];
/* IXPCI device information for found cards' list */
typedef struct ixpci_kernel {
struct ixpci_kernel *next; /* next device (ixpci card) */
struct ixpci_kernel *prev; /* previous device */
struct ixpci_kernel *next_f; /* next device in same family */
struct ixpci_kernel *prev_f; /* previous device in same family */
unsigned int no; /* device number (minor number) */
__u64 id; /* card's id */
unsigned int open; /* open counter */
struct file_operations *fops; /* file operations for this device */
char name[CNL]; /* card name information */
struct pci_dev *sdev; /* The PCI device (we need to release
it on driver unload */
} ixpci_kernel_t;
/* from pci.c */
void *ixpci_pci_cardname(__u64);
void ixpci_copy_devinfo(ixpci_devinfo_t * dst, ixpci_kernel_t * src);
extern unsigned int ixpci_major;
extern ixpci_kernel_t *ixpci_dev;
/* from proc.c */
int ixpci_proc_init(void);
void ixpci_proc_exit(void);
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/apps/server-e/impl/stargate/usermarshall.c | <filename>eon/apps/server-e/impl/stargate/usermarshall.c
#include "usermarshall.h"
#include "rt_structs.h"
#include <stdint.h>
int unmarshall_RequestMsg(int cid, RequestMsg *data)
{
int result;
int i=0;
dbg(APP,"umarsh_RequestMsg:\n");
result = unmarshall_uint16_t(cid, &data->src);
if (result) return -1;
dbg(APP,"src=%i\n",data->src);
result = unmarshall_uint16_t(cid, &data->suid);
if (result) return -1;
dbg(APP,"suid=%i\n",data->suid);
for (i=0; i < URL_LENGTH; i++)
{
result = unmarshall_uint8_t(cid, &data->url[i]);
if (result) return -1;
dbg(APP,"%X ",data->url[i]);
}
return 0;
}
//************************************************
//MARSHALLING FUNCS
//************************************************/
|
tinyos-io/tinyos-3.x-contrib | diku/mcs51/tos/chips/cc2430/ioCC2430.h | <filename>diku/mcs51/tos/chips/cc2430/ioCC2430.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.
*/
/**
*
* Provide cc2430 specific register maps
*
* Absolute addressing in Keil is possible in a number of ways:
* Standard C
* (uint8_t xdata*) addr
* Using sfr types/storrage class specifiers
* sfr x = addr
* Using the at modifier
* uint8_t x at addr
*
* Regarding multibyte values, it seems that ChipCon has chosen the
* follwing semantics that handles latching one or more bytes when
* reading and writing:
*
* When reading: the _low_ byte must be read first and the high-byte
* is latched for glitch free 16-bit operations
*
* When writing: the low byte must be written first and the value
* does not take effect before the high byte is written
*
*
* @author <NAME> <<EMAIL>>
*/
#ifndef _H_ioCC2430_H
#define _H_ioCC2430_H
// Get sfr/sbit dummy definitions
# include <io8051.h>
/*
* Bit locations for IEN0
*/
enum {
CC2430_IEN0_EA = 0x7,
CC2430_IEN0_STIE = 0x5,
CC2430_IEN0_ENCIE = 0x4,
CC2430_IEN0_URX1IE = 0x3,
CC2430_IEN0_URX0IE = 0x2,
CC2430_IEN0_ADCIE = 0x1,
CC2430_IEN0_RFERRIE = 0x0
};
/*
* Bit locations for IEN2
*/
enum {
CC2430_IEN2_WDTIE = 0x5,
CC2430_IEN2_P1IE = 0x4,
CC2430_IEN2_UTX1IE = 0x3,
CC2430_IEN2_UTX0IE = 0x2,
CC2430_IEN2_P2IE = 0x1,
CC2430_IEN2_RFIE = 0x0
};
/*
* Bit locations for IRCON
*/
enum {
CC2430_IRCON_STIF = 0x7,
CC2430_IRCON_P0IF = 0x5,
CC2430_IRCON_T4IF = 0x4,
CC2430_IRCON_T3IF = 0x3,
CC2430_IRCON_T2IF = 0x2,
CC2430_IRCON_T1IF = 0x1,
CC2430_IRCON_DMAIF = 0x0
};
/*
* Bit locations for IRCON2
*/
enum {
CC2430_IRCON2_WDTIF = 0x4,
CC2430_IRCON2_P1IF = 0x3,
CC2430_IRCON2_UTX1IF = 0x2,
CC2430_IRCON2_UTX0IF = 0x1,
CC2430_IRCON2_P2IF = 0x0
};
/*
* Bit locations for RFIM
*/
enum {
CC2430_RFIM_RREG_PD = 0x7,
CC2430_RFIM_TXDONE = 0x6,
CC2430_RFIM_FIFOP = 0x5,
CC2430_RFIM_SFD = 0x4,
CC2430_RFIM_CCA = 0x3,
CC2430_RFIM_CSP_WT = 0x2,
CC2430_RFIM_CSP_STOP = 0x1,
CC2430_RFIM_CSP_INT = 0x0
};
/*
* Bit locations for RFIF
*/
enum {
CC2430_RFIF_RREG_ON = 0x7,
CC2430_RFIF_TXDONE = 0x6,
CC2430_RFIF_FIFOP = 0x5,
CC2430_RFIF_SFD = 0x4,
CC2430_RFIF_CCA = 0x3,
CC2430_RFIF_CSP_WT = 0x2,
CC2430_RFIF_CSP_STOP = 0x1,
CC2430_RFIF_CSP_INT = 0x0
};
// Interrupt definitions
#define SIG_RFERR __vector_0 /* RF TX FIFO Underflow and RX FIFO Overflow */
#define SIG_ADC __vector_1 /* ADC End of Conversion */
#define SIG_URX0 __vector_2 /* USART0 RX Complete */
#define SIG_URX1 __vector_3 /* USART1 RX Complete */
#define SIG_ENC __vector_4 /* AES Encryption/Decryption Complete */
#define SIG_ST __vector_5 /* Sleep Timer Compare */
#define SIG_P2INT __vector_6 /* Port 2 Inputs */
#define SIG_UTX0 __vector_7 /* USART0 TX Complete */
#define SIG_DMA __vector_8 /* DMA Transfer Complete */
#define SIG_T1 __vector_9 /* Timer 1 (16-bit) Capture/Compare/Overflow */
#define SIG_T2 __vector_10 /* Timer 2 (MAC Timer) */
#define SIG_T3 __vector_11 /* Timer 3 (8-bit) Capture/Compare/Overflow */
#define SIG_T4 __vector_12 /* Timer 4 (8-bit) Capture/Compare/Overflow */
#define SIG_P0INT __vector_13 /* Port 0 Inputs */
#define SIG_UTX1 __vector_14 /* USART1 TX Complete */
#define SIG_P1INT __vector_15 /* Port 1 Inputs */
#define SIG_RF __vector_16 /* RF General Interrupts */
#define SIG_WDT __vector_17 /* Watchdog Overflow in Timer Mode */
uint8_t volatile U0CSR __attribute((sfrAT0x86)); /* USART 0 Control and Status */
//uint8_t volatile TCON __attribute((sfrAT0x88));
uint8_t volatile P0IFG __attribute((sfrAT0x89)); /* Port 0 Interrupt Status Flag */
uint8_t volatile P1IFG __attribute((sfrAT0x8A)); /* Port 1 Interrupt Status Flag */
uint8_t volatile P2IFG __attribute((sfrAT0x8B)); /* Port 2 Interrupt Status Flag */
uint8_t volatile PICTL __attribute((sfrAT0x8C)); /* Port Interrupt Control */
uint8_t volatile P1IEN __attribute((sfrAT0x8D)); /* Port 1 Interrupt Mask */
uint8_t volatile P0INP __attribute((sfrAT0x8F)); /* Port 0 Input Mode */
/* TCON sbit definitions */
uint8_t volatile URX1IF __attribute((sbitAT0x8F)); /* USART1 RX Interrupt Flag */
uint8_t volatile _TCON6 __attribute((sbitAT0x8E)); /* not used */
uint8_t volatile ADCIF __attribute((sbitAT0x8D)); /* ADC Interrupt Flag */
uint8_t volatile _TCON5 __attribute((sbitAT0x8C)); /* not used */
uint8_t volatile URX0IF __attribute((sbitAT0x8B)); /* USART0 RX Interrupt Flag */
uint8_t volatile IT1 __attribute((sbitAT0x8A)); /* reserved (must always be set to 1)*/
uint8_t volatile RFERRIF __attribute((sbitAT0x89)); /* RF TX/RX FIFO Interrupt Flag */
uint8_t volatile IT0 __attribute((sbitAT0x88)); /* reserved (must always be set to 1)*/
/* Port 1 */
// io8051.h uint8_t volatile P1 __attribute((sfrAT0x90));
uint8_t volatile RFIM __attribute((sfrAT0x91)); /* RF Interrupt Mask */
uint8_t volatile DPS __attribute((sfrAT0x92)); /* Data Pointer Select */
uint8_t volatile MPAGE __attribute((sfrAT0x93)); /* Memory Page Select */
uint8_t volatile T2CMP __attribute((sfrAT0x94)); /* Timer 2 Compare Value */
uint8_t volatile ST0 __attribute((sfrAT0x95)); /* Sleep Timer 0 */
uint8_t volatile ST1 __attribute((sfrAT0x96)); /* Sleep Timer 1 */
uint8_t volatile ST2 __attribute((sfrAT0x97)); /* Sleep Timer 2 */
/* Interrupt Enable 2 - IEN2 sfr */
uint8_t volatile IEN2 __attribute((sfrAT0x9A)); /* Interrupt Enable 2 */
uint8_t volatile S1CON __attribute((sfrAT0x9B)); /* Interrupt Flags 3 */
uint8_t volatile T2PEROF0 __attribute((sfrAT0x9C)); /* Timer 2 Overflow Count 0 */
uint8_t volatile T2PEROF1 __attribute((sfrAT0x9D)); /* Timer 2 Overflow Count 1 */
uint8_t volatile T2PEROF2 __attribute((sfrAT0x9E)); /* Timer 2 Overflow Count 2 */
uint8_t volatile T2OF0 __attribute((sfrAT0xA1)); /* Timer 2 Overflow Count 0 */
uint8_t volatile T2OF1 __attribute((sfrAT0xA2)); /* Timer 2 Overflow Count 1 */
uint8_t volatile T2OF2 __attribute((sfrAT0xA3)); /* Timer 2 Overflow Count 2 */
uint8_t volatile T2CAPLPL __attribute((sfrAT0xA4)); /* Timer 2 Period Low Byte */
uint8_t volatile T2CAPHPH __attribute((sfrAT0xA5)); /* Timer 2 Period High Byte */
uint8_t volatile T2TLD __attribute((sfrAT0xA6)); /* Timer 2 Timer Value Low Byte */
uint8_t volatile T2THD __attribute((sfrAT0xA7)); /* Timer 2 Timer Value High Byte*/
/* Interrupt Enable 0 */
uint8_t volatile IEN0 __attribute((sbitAT0xA8)); /* Also known as IE */
uint8_t volatile RFERRIE __attribute((sbitAT0xA8)); /* RF TX/RX FIFO Interrupt Enable */
uint8_t volatile ADCIE __attribute((sbitAT0xA9)); /* ADC Interrupt Enable */
uint8_t volatile URX0IE __attribute((sbitAT0xAA)); /* USART0 RX Interrupt Enable */
uint8_t volatile URX1IE __attribute((sbitAT0xAB)); /* USART1 RX Interrupt Enable */
uint8_t volatile ENCIE __attribute((sbitAT0xAC)); /* AES Interrupt Enable */
uint8_t volatile STIE __attribute((sbitAT0xAD)); /* Sleep Timer Interrupt Enable */
uint8_t volatile FWT __attribute((sfrAT0xAB));
uint8_t volatile FADDRL __attribute((sfrAT0xAC));
uint8_t volatile FADDRH __attribute((sfrAT0xAD));
uint8_t volatile FCTL __attribute((sfrAT0xAE));
uint8_t volatile FWDATA __attribute((sfrAT0xAF));
/* Interrupt Enable 1 */
uint8_t volatile IEN1 __attribute((sfrAT0xB8)); /* CC2430 specific interrupt mask */
uint8_t volatile _IEN17 __attribute((sbitAT0xBF)); /* not used */
uint8_t volatile _IEN16 __attribute((sbitAT0xBE)); /* not used */
uint8_t volatile P0IE __attribute((sbitAT0xBD)); /* Port 0 Interrupt Enable */
uint8_t volatile T4IE __attribute((sbitAT0xBC)); /* Timer 4 Interrupt Enable */
uint8_t volatile T3IE __attribute((sbitAT0xBB)); /* Timer 3 Interrupt Enable */
uint8_t volatile T2IE __attribute((sbitAT0xBA)); /* Timer 2 Interrupt Enable */
uint8_t volatile T1IE __attribute((sbitAT0xB9)); /* Timer 1 Interrupt Enable */
uint8_t volatile DMAIE __attribute((sbitAT0xB8)); /* DMA Interrupt Enable */
uint8_t volatile ENCDI __attribute((sfrAT0xB1)); /* Encryption Input Data */
uint8_t volatile ENCDO __attribute((sfrAT0xB2)); /* Encryption Output Data */
uint8_t volatile ENCCS __attribute((sfrAT0xB3)); /* Encryption Control and Status */
uint8_t volatile ADCCON1 __attribute((sfrAT0xB4)); /* ADC Control 1 */
uint8_t volatile ADCCON2 __attribute((sfrAT0xB5)); /* ADC Control 2 */
uint8_t volatile ADCCON3 __attribute((sfrAT0xB6)); /* ADC Control 3 */
uint8_t volatile IEN1 __attribute((sfrAT0xB8)); /* Defined in io8051.h */
uint8_t volatile IP1 __attribute((sfrAT0xB9)); /* Interrupt Priority 1 */
uint8_t volatile ADCL __attribute((sfrAT0xBA)); /* ADC Data Low */
uint8_t volatile ADCH __attribute((sfrAT0xBB)); /* ADC Data High */
uint8_t volatile RNDL __attribute((sfrAT0xBC)); /* Random Register Low Byte */
uint8_t volatile RNDH __attribute((sfrAT0xBD)); /* Random Register High Byte */
uint8_t volatile SLEEP __attribute((sfrAT0xBE)); /* Sleep Mode Control */
uint8_t volatile _SFRBF __attribute((sfrAT0xBF)); /* not used */
norace uint8_t volatile U0BUF __attribute((sfrAT0xC1)); /* USART 0 Rx/Tx Data Buffer */
uint8_t volatile U0BAUD __attribute((sfrAT0xC2)); /* USART 0 Baud Rate Control */
uint8_t volatile T2CNF __attribute((sfrAT0xC3)); /* Timer 2 Configuration */
uint8_t volatile U0UCR __attribute((sfrAT0xC4)); /* USART 0 UART Control */
uint8_t volatile U0GCR __attribute((sfrAT0xC5)); /* USART 0 Generic Control */
uint8_t volatile CLKCON __attribute((sfrAT0xC6)); /* Clock Control */
uint8_t volatile MEMCTR __attribute((sfrAT0xC7)); /* Memory Arbiter Control */
uint8_t volatile T2CON __attribute((sfrAT0xC8)); /* Interrupt Control */
uint8_t volatile WDCTL __attribute((sfrAT0xC9)); /* Watchdog Timer Control */
uint8_t volatile T3CNT __attribute((sfrAT0xCA)); /* Timer 3 Counter */
uint8_t volatile T3CTL __attribute((sfrAT0xCB)); /* Timer 3 Control */
uint8_t volatile T3CCTL0 __attribute((sfrAT0xCC)); /* Timer 3 Ch 0 Capture/Compare Control */
uint8_t volatile T3CC0 __attribute((sfrAT0xCD)); /* Timer 3 Ch 0 Capture/Compare Value */
uint8_t volatile T3CCTL1 __attribute((sfrAT0xCE)); /* Timer 3 Ch 1 Capture/Compare Control */
uint8_t volatile T3CC1 __attribute((sfrAT0xCF)); /* Timer 3 Ch 1 Capture/Compare Value */
/* Timers 1/3/4 Interrupt Mask/Flag */
uint8_t volatile TIMIF __attribute((sfrAT0xD8));
uint8_t volatile _TIMIF7 __attribute((sbitAT0xDF)); /* not used */
uint8_t volatile OVFIM __attribute((sbitAT0xDE)); /* Timer 1 Overflow Interrupt Mask */
uint8_t volatile T4CH1IF __attribute((sbitAT0xDD)); /* Timer 4 Channel 1 Interrupt Flag */
uint8_t volatile T4CH0IF __attribute((sbitAT0xDC)); /* Timer 4 Channel 0 Interrupt Flag */
uint8_t volatile T4OVFIF __attribute((sbitAT0xDB)); /* Timer 4 Overflow Interrupt Flag */
uint8_t volatile T3CH1IF __attribute((sbitAT0xDA)); /* Timer 3 Channel 1 Interrupt Flag */
uint8_t volatile T3CH0IF __attribute((sbitAT0xD9)); /* Timer 3 Channel 0 Interrupt Flag */
uint8_t volatile T3OVFIF __attribute((sbitAT0xD8)); /* Timer 3 Overflow Interrupt Flag */
uint8_t volatile RFD __attribute((sfrAT0xD9)); /* RF Data */
uint16_t volatile T1CC0 __attribute((sfr16AT0xDA));/* Timer 1 Ch 0 Capture/Compare Value */
uint8_t volatile T1CC0L __attribute((sfrAT0xDA)); /* Timer 1 Ch 0 Capture/Compare Value Low */
uint8_t volatile T1CC0H __attribute((sfrAT0xDB)); /* Timer 1 Ch 0 Capture/Compare Value High */
uint16_t volatile T1CC1 __attribute((afr16AT0xDC));/* Timer 1 Ch 1 Capture/Compare Value */
uint8_t volatile T1CC1L __attribute((sfrAT0xDC)); /* Timer 1 Ch 1 Capture/Compare Value Low */
uint8_t volatile T1CC1H __attribute((sfrAT0xDD)); /* Timer 1 Ch 1 Capture/Compare Value High */
uint16_t volatile T1CC2 __attribute((sfr16AT0xDE));/* Timer 1 Ch 2 Capture/Compare Value */
uint8_t volatile T1CC2L __attribute((sfrAT0xDE)); /* Timer 1 Ch 2 Capture/Compare Value Low */
uint8_t volatile T1CC2H __attribute((sfrAT0xDF)); /* Timer 1 Ch 2 Capture/Compare Value High */
uint8_t volatile DMAREQ __attribute((sfrAT0xD7)); /* DMA Channel Start Request and Status */
uint8_t volatile DMAARM __attribute((sfrAT0xD6)); /* DMA Channel Arm */
uint8_t volatile DMA0CFGH __attribute((sfrAT0xD5));/* DMA Ch 0 Configuration Address High */
uint8_t volatile DMA0CFGL __attribute((sfrAT0xD4));/* DMA Ch 0 Configuration Address Low Byte */
uint8_t volatile DMA1CFGH __attribute((sfrAT0xD3));/* DMA Ch 1-4 Configuration Address High */
uint8_t volatile DMA1CFGL __attribute((sfrAT0xD2));/* DMA Ch 1-4 Configuration Address Low */
uint8_t volatile DMAIRQ __attribute((sfrAT0xD1));/* DMA Interrupt Flag */
uint8_t volatile ACC __attribute((sfrAT0xE0)); /* Accumulator */
uint8_t volatile RFST __attribute((sfrAT0xE1)); /* RF CSMA-CA / Strobe Processor */
uint16_t volatile T1CNT __attribute((sfr16xE2)); /* Timer 1 Counter */
uint8_t volatile T1CNTL __attribute((sfrAT0xE2)); /* Timer 1 Counter Low */
uint8_t volatile T1CNTH __attribute((sfrAT0xE3)); /* Timer 1 Counter High */
uint8_t volatile T1CTL __attribute((sfrAT0xE4)); /* Timer 1 Control and Status */
uint8_t volatile T1CCTL0 __attribute((sfrAT0xE5)); /* Timer 1 Ch 0 Capture/Compare Control */
uint8_t volatile T1CCTL1 __attribute((sfrAT0xE6)); /* Timer 1 Ch 1 Capture/Compare Control */
uint8_t volatile T1CCTL2 __attribute((sfrAT0xE7)); /* Timer 1 Ch 2 Capture/Compare Control */
/* Bit register definitions for interrupt mask IRCON1 */
uint8_t volatile STIF __attribute((sbitAT0xC7)); /* Sleep Timer */
uint8_t volatile _IRCON16 __attribute((sbitAT0xC6)); /* not used */
uint8_t volatile P0IF __attribute((sbitAT0xC5)); /* Port 0 Interrupt Flag */
uint8_t volatile T4IF __attribute((sbitAT0xC4)); /* Timer 4 Interrupt Flag */
uint8_t volatile T3IF __attribute((sbitAT0xC3)); /* Timer 3 Interrupt Flag */
uint8_t volatile T2IF __attribute((sbitAT0xC2)); /* Timer 2 Interrupt Flag */
uint8_t volatile T1IF __attribute((sbitAT0xC1)); /* Timer 1 Interrupt Flag */
uint8_t volatile DMAIF __attribute((sbitAT0xC0)); /* DMA Complete Interrupt Flag */
/* Bit register definitions for interrupt mask IRCON2 */
uint8_t volatile _IRCON27 __attribute((sbitAT0xEF)); /* not used */
uint8_t volatile _IRCON26 __attribute((sbitAT0xEE)); /* not used */
uint8_t volatile _IRCON25 __attribute((sbitAT0xED)); /* not used */
uint8_t volatile WDTIF __attribute((sbitAT0xEC)); /* Watchdog Timer Interrupt Flag */
uint8_t volatile P1IF __attribute((sbitAT0xEB)); /* Port 1 Interrupt Flag */
uint8_t volatile UTX1IF __attribute((sbitAT0xEA)); /* USART1 TX Interrupt Flag */
uint8_t volatile UTX0IF __attribute((sbitAT0xE9)); /* USART0 TX Interrupt Flag */
uint8_t volatile P2IF __attribute((sbitAT0xE8)); /* Port 2 Interrupt Flag */
uint8_t volatile IRCON2 __attribute((sfrAT0xE8)); /* Interrupt Flags 5 */
uint8_t volatile RFIF __attribute((sfrAT0xE9)); /* RF Interrupt Flags */
uint8_t volatile T4CNT __attribute((sfrAT0xEA)); /* Timer 4 Counter */
uint8_t volatile T4CTL __attribute((sfrAT0xEB)); /* Timer 4 Control */
uint8_t volatile T4CCTL0 __attribute((sfrAT0xEC)); /* Timer 4 Ch 0 Capture/Compare Control */
uint8_t volatile T4CC0 __attribute((sfrAT0xED)); /* Timer 4 Ch 0 Capture/Compare Value */
uint8_t volatile T4CCTL1 __attribute((sfrAT0xEE)); /* Timer 4 Ch 1 Capture/Compare Control */
uint8_t volatile T4CC1 __attribute((sfrAT0xEF)); /* Timer 4 Ch 1 Capture/Compare Value */
uint8_t volatile B __attribute((sfrAT0xF0)); /* B Register */
uint8_t volatile PERCFG __attribute((sfrAT0xF1)); /* Peripheral Control */
uint8_t volatile ADCCFG __attribute((sfrAT0xF2)); /* ADC Input Configuration */
uint8_t volatile P1INP __attribute((sfrAT0xF6)); /* Port 1 Input Mode */
uint8_t volatile P2INP __attribute((sfrAT0xF7)); /* Port 2 Input Mode */
uint8_t volatile P0_DIR __attribute((sfrAT0xFD));
uint8_t volatile P1_DIR __attribute((sfrAT0xFE));
uint8_t volatile P2_DIR __attribute((sfrAT0xFF));
// This is denoted as P0SEL, but for consistency we name it this way
uint8_t volatile P0_ALT __attribute((sfrAT0xF3));
// This is denoted as P1SEL, but for consistency we name it this way
uint8_t volatile P1_ALT __attribute((sfrAT0xF4));
// This is denoted as P2SEL, but for consistency we name it this way
uint8_t volatile P2_ALT __attribute((sfrAT0xF5));
/* ------------------------------------------------------------------------------------------------
* Xdata Radio Registers
* ------------------------------------------------------------------------------------------------
*/
/*
* Note: these registers are located in the xdata memory area, not sfr
* - therefore the sfr16 types cannot be used. Instead the variables
* have to be assigned to xdata space using appropriate storrage
* clases using the mangle script.
*
* uint16_t values are stored as big ending (MSB first, see io8051.h)
* so in the following definitions high order byte (MSB) is selected
* as the address for uint16 values.
*
* The registers are not double buffered (latched) and thus the
* read/write order does not make a difference.
*
*
* As an alternative you could imagine defining these as variables
* with absolute locations:
* uint8_t xdata MDMCTRL0H_VAR at addr;
*
* However mangling this in a compiler agnostic way is probaby more
* difficult than stickting to something that looks like ANSI-C
*
*
*/
typedef uint16_t uint16_t_xdata; // will be replaced by uint16_t xdata
typedef uint8_t uint8_t_xdata; // will be replaced by uint8_t xdata
typedef uint16_t uint16_t_code; // will be replaced by uint16_t code
typedef uint8_t uint8_t_code; // will be replaced by uint8_t code
// I would say these should be volatile, but nesc throws up
//#define _XIO16(addr) (*((volatile unint16_t_xdata*) addr))
//#define _XIO8(addr) (*((uint8_t volatile_xdata*) addr))
#define _XIO16(addr) (*(( uint16_t_xdata*) addr))
#define _XIO8(addr) (*(( uint8_t_xdata*) addr))
#define _CC2430_MDMCTRL0 _XIO16(0xDF02 ) /* Modem Control 0 */
#define _CC2430_MDMCTRL0H _XIO8( 0xDF02 ) /* Modem Control 0 High Byte */
#define _CC2430_MDMCTRL0L _XIO8( 0xDF03 ) /* Modem Control 0 Low Byte */
#define _CC2430_MDMCTRL1 _XIO16(0xDF04 ) /* Modem Control 1 */
#define _CC2430_MDMCTRL1H _XIO8( 0xDF04 ) /* Modem Control 1 High Byte */
#define _CC2430_MDMCTRL1L _XIO8( 0xDF05 ) /* Modem Control 1 Low Byte */
#define _CC2430_RSSIH _XIO8( 0xDF06 ) /* RSSI and CCA Status and Control High Byte */
#define _CC2430_RSSIL _XIO8( 0xDF07 ) /* RSSI and CCA Status and Control Low Byte */
#define _CC2430_SYNCWORD _XIO16(0xDF08 ) /* Synchronization and Control */
#define _CC2430_SYNCWORDH _XIO8( 0xDF08 ) /* Synchronization and Control High Byte */
#define _CC2430_SYNCWORDL _XIO8( 0xDF09 ) /* Synchronization and Control Low Byte */
#define _CC2430_TXCTRL _XIO16(0xDF0A ) /* Transmit Control */
#define _CC2430_TXCTRLH _XIO8( 0xDF0A ) /* Transmit Control High Byte */
#define _CC2430_TXCTRLL _XIO8( 0xDF0B ) /* Transmit Control Low Byte */
#define _CC2430_RXCTRL0 _XIO16(0xDF0C ) /* Receive Control 0 */
#define _CC2430_RXCTRL0H _XIO8( 0xDF0C ) /* Receive Control 0 High Byte */
#define _CC2430_RXCTRL0L _XIO8( 0xDF0D ) /* Receive Control 0 Low Byte */
#define _CC2430_RXCTRL1 _XIO8( 0xDF0E ) /* Receive Control 1 */
#define _CC2430_RXCTRL1H _XIO8( 0xDF0E ) /* Receive Control 1 High Byte */
#define _CC2430_RXCTRL1L _XIO8( 0xDF0F ) /* Receive Control 1 Low Byte */
#define _CC2430_FSCTRL _XIO16(0xDF10 ) /* Frequency Synthesizer Control and Status */
#define _CC2430_FSCTRLH _XIO8( 0xDF10 ) /* Frequency Synthesizer Control and Status High Byte*/
#define _CC2430_FSCTRLL _XIO8( 0xDF11 ) /* Frequency Synthesizer Control and Status Low Byte */
#define _CC2430_CSPX _XIO8( 0xDF12 ) /* CSMA/CA Strobe Processor X Data Register */
#define _CC2430_CSPY _XIO8( 0xDF13 ) /* CSMA/CA Strobe Processor Y Data Register */
#define _CC2430_CSPZ _XIO8( 0xDF14 ) /* CSMA/CA Strobe Processor Z Data Register */
#define _CC2430_CSPCTRL _XIO8( 0xDF15 ) /* CSMA/CA Strobe Processor CPU Control Input */
#define _CC2430_CSPT _XIO8( 0xDF16 ) /* CSMA/CA Strobe Processor T Data Register */
#define _CC2430_RFPWR _XIO8( 0xDF17 ) /* Radio Power */
#define _CC2430_FSMTCH _XIO8( 0xDF20 ) /* Finite State Machine Time Constants High Byte */
#define _CC2430_FSMTCL _XIO8( 0xDF21 ) /* Finite State Machine Time Constants Low Byte */
#define _CC2430_MANANDH _XIO8( 0xDF22 ) /* Manual Signal AND Override High Byte */
#define _CC2430_MANANDL _XIO8( 0xDF23 ) /* Manual Signal AND Override Low Byte */
#define _CC2430_MANORH _XIO8( 0xDF24 ) /* Manual Signal OR Override High Byte */
#define _CC2430_MANORL _XIO8( 0xDF25 ) /* Manual Signal OR Override High Byte */
#define _CC2430_AGCCTRLH _XIO8( 0xDF26 ) /* AGC Control High Byte */
#define _CC2430_AGCCTRLL _XIO8( 0xDF27 ) /* AGC Control Low Byte */
#define _CC2430_FSMSTATE _XIO8( 0xDF39 ) /* Finite State Machine State */
#define _CC2430_ADCTSTH _XIO8( 0xDF3A ) /* ADC Test High Byte */
#define _CC2430_ADCTSTL _XIO8( 0xDF3B ) /* ADC Test Low Byte */
#define _CC2430_DACTSTH _XIO8( 0xDF3C ) /* DAC Test High Byte */
#define _CC2430_DACTSTL _XIO8( 0xDF3D ) /* DAC Test Low Byte */
#define _CC2430_IEEE_ADDR0 _XIO8( 0xDF43 ) /* IEEE Address Byte 0 (LSB) */
#define _CC2430_IEEE_ADDR1 _XIO8( 0xDF44 ) /* IEEE Address Byte 1 */
#define _CC2430_IEEE_ADDR2 _XIO8( 0xDF45 ) /* IEEE Address Byte 2 */
#define _CC2430_IEEE_ADDR3 _XIO8( 0xDF46 ) /* IEEE Address Byte 3 */
#define _CC2430_IEEE_ADDR4 _XIO8( 0xDF47 ) /* IEEE Address Byte 4 */
#define _CC2430_IEEE_ADDR5 _XIO8( 0xDF48 ) /* IEEE Address Byte 5 */
#define _CC2430_IEEE_ADDR6 _XIO8( 0xDF49 ) /* IEEE Address Byte 6 */
#define _CC2430_IEEE_ADDR7 _XIO8( 0xDF4A ) /* IEEE Address Byte 7 (MSB) */
#define _CC2430_PANID _XIO16(0xDF4B ) /* PAN Identifier */
#define _CC2430_PANIDH _XIO8( 0xDF4B ) /* PAN Identifier High Byte */
#define _CC2430_PANIDL _XIO8( 0xDF4C ) /* PAN Identifier Low Byte */
#define _CC2430_SHORTADDR _XIO16(0xDF4D ) /* Short Address */
#define _CC2430_SHORTADDRH _XIO8( 0xDF4D ) /* Short Address High Byte */
#define _CC2430_SHORTADDRL _XIO8( 0xDF4E ) /* Short Address Low Byte */
#define _CC2430_IOCFG01 _XIO16(0xDF4F ) /* Input/Output Control 0+1 */
#define _CC2430_IOCFG0 _XIO8( 0xDF4F ) /* Input/Output Control 0 */
#define _CC2430_IOCFG1 _XIO8( 0xDF50 ) /* Input/Output Control 1 */
#define _CC2430_IOCFG23 _XIO16(0xDF51 ) /* Input/Output Control 2+3 */
#define _CC2430_IOCFG2 _XIO8( 0xDF51 ) /* Input/Output Control 2 */
#define _CC2430_IOCFG3 _XIO8( 0xDF52 ) /* Input/Output Control 3 */
#define _CC2430_RXFIFOCNT _XIO8( 0xDF53 ) /* Receive FIFO Count */
#define _CC2430_FSMTC1 _XIO8( 0xDF54 ) /* Finite State Machine Time Constants */
#define _CC2430_CHVER _XIO8( 0xDF60 ) /* Chip Revision Number */
#define _CC2430_CHIPID _XIO8( 0xDF61 ) /* Chip ID Number */
#define _CC2430_RFSTATUS _XIO8( 0xDF62 ) /* Radio Status */
/* Bit fields for xdata registers */
enum {
CC2430_RFPWR_ADI_RADIO_PD = 0x4,
CC2430_RFPWR_RREG_RADIO_PD = 0x3,
CC2430_RFPWR_RREG_DELAY = 0x0, // 3 bit field
CC2430_RFPWR_RREG_DELAY_MASK = 0x7
};
enum {
CC2430_RREG_DELAY_0 = 0x0, // 0 us delay
CC2430_RREG_DELAY_31 = 0x1, // 31 us delay
CC2430_RREG_DELAY_63 = 0x2, // 63 us delay
CC2430_RREG_DELAY_125 = 0x3, // 125 us delay
CC2430_RREG_DELAY_250 = 0x4, // 250 us delay
CC2430_RREG_DELAY_500 = 0x5, // 500 us delay
CC2430_RREG_DELAY_1000 = 0x6, // 1000 us delay
CC2430_RREG_DELAY_2000 = 0x7 // 2000 us delay
};
enum {
CC2430_MDMCTRL0L_AUTOCRC = 0x5,
CC2430_MDMCTRL0L_AUTOACK = 0x4
};
enum {
CC2430_MDMCTRL0H_FRAME_FILT = 0x6, // 2-bit field
CC2430_MDMCTRL0H_RESERVED_FRAME_MODE = 0x5,
CC2430_MDMCTRL0H_PAN_COORDINATOR = 0x4,
CC2430_MDMCTRL0H_ADDR_DECODE = 0x3,
CC2430_MDMCTRL0H_CCA_HYST = 0x0 // 3-bit field
};
enum {
CC2430_RFSTATUS_TX_ACTIVE = 0x4,
CC2430_RFSTATUS_FIFO = 0x3,
CC2430_RFSTATUS_FIFOP = 0x2,
CC2430_RFSTATUS_SFD = 0x1,
CC2430_RFSTATUS_CCA = 0x0
};
#endif // _H_ioCC2430_H
|
tinyos-io/tinyos-3.x-contrib | diku/freescale/tos/chips/mc13192/mc13192Const.h | <gh_stars>1-10
/* Copyright (c) 2006, <NAME> <<EMAIL>>
* 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 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 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> <<EMAIL>>
*/
#ifndef _MC13192CONST_H_
#define _MC13192CONST_H_
/**************************************************************
* Defines
* MC13192 status register interrupt masks.
**************************************************************/
// MC13192 Register 05
#define TIMER1_IRQMASK_BIT 0x0001
#define TIMER2_IRQMASK_BIT 0x0002
#define TIMER3_IRQMASK_BIT 0x0004
#define TIMER4_IRQMASK_BIT 0x0008
#define DOZE_IRQMASK_BIT 0x0010
#define LO1_LOCK_IRQMASK_BIT 0x0200
#define STRM_DATA_IRQMASK_BIT 0x0400
#define ARB_BUSY_IRQMASK_BIT 0x0800
#define RAM_ADDR_IRQMASK_BIT 0x1000
#define ATTN_IRQMASK_BIT 0x8000
// MC13192 Register 24
#define CRC_VALID_MASK 0x0001
#define CCA_STATUS_MASK 0x0002
#define TIMER2_IRQ_MASK 0x0004
#define TIMER4_IRQ_MASK 0x0008
#define TIMER3_IRQ_MASK 0x0010
#define CCA_IRQ_MASK 0x0020
#define TX_IRQ_MASK 0x0040
#define RX_IRQ_MASK 0x0080
#define TIMER1_IRQ_MASK 0x0100
#define DOZE_IRQ_MASK 0x0200
#define ATTN_IRQ_MASK 0x0400
#define HG_IRQ_MASK 0x0800
#define STRM_DATA_ERR_IRQ_MASK 0x1000
#define STRM_RX_DONE_IRQ_MASK 0x2000
#define ARB_BUSY_ERR_IRQ_MASK 0x2000
#define STRM_TX_DONE_IRQ_MASK 0x4000
#define RAM_ADDR_ERR_IRQ_MASK 0x4000
#define LO_LOCK_IRQ_MASK 0x8000
// MC13192 Register 25
#define RESET_BIT_MASK 0x0080
/**************************************************************
* Defines
* The MC13192 transceiver register map.
**************************************************************/
/******** MC13192 soft reset **********/
#define RESET 0x00
/******** Packet RAM **********/
#define RX_PKT_RAM 0x01 // RX Packet RAM
#define RX_STATUS 0x2D // RX Packet RAM Length [6:0]
#define TX_PKT_RAM 0x02 // TX Packet RAM
#define TX_PKT_CTL 0x03 // TX Packet RAM Length
/******** IRQ Status Register *******/
#define IRQ_MASK 0x05
#define IRQ_STATUS 0x24
#define RST_IND 0x25
/******** Control Registers **********/
#define CONTROL_A 0x06
#define CONTROL_B 0x07
#define CONTROL_C 0x09
#define LO1_COURSE_TUNE 0x8000
/******** Main Timer **********/
#define CURRENT_TIME_A 0x26
#define CURRENT_TIME_B 0x27
#define TIMESTAMP_A 0x2E
#define TIMESTAMP_B 0x2F
#define TIMESTAMP_HI_MASK 0x00FF
/******** frequency ***************/
#define CLKO_CTL 0x0A
#define LO1_INT_DIV 0x0F
#define LO1_NUM 0x10
/******** Timer comparators **********/
#define TMR_CMP1_A 0x1B
#define TMR_CMP1_B 0x1C
#define TMR_CMP2_A 0x1D
#define TMR_CMP2_B 0x1E
#define TMR_CMP3_A 0x1F
#define TMR_CMP3_B 0x20
#define TMR_CMP4_A 0x21
#define TMR_CMP4_B 0x22
#define TC2_PRIME 0x23
/******** CCA **********/
#define CCA_THRESH 0x04
/******** TX ***********/
#define PA_LVL 0x12
/******* GPIO **********/
#define GPIO_DIR 0x0B
#define GPIO_DATA_OUT 0x0C
#define GPIO_DATA_IN 0x28
#define GPIO_DATA_MASK 0x003F
/******* version *******/
#define CHIP_ID 0x2C
#define MASK_SET_ID_MASK 0xE000
#define VERSION_MASK 0x1C00
#define MANUFACTURER_ID_MASK 0x0380
/**************************************************************
* Defines
* Modes for the MC13192 transceiver.
**************************************************************/
// These modes corresponds to register 6 settings.
// Remember to set the hidden bit 14.
#define IDLE_MODE 0x4000
#define CCA_MODE 0x4411
#define ED_MODE 0x4421
#define RX_MODE 0x4102 // Was: 0x4102
#define TX_MODE 0x4203 // Was: 0x4203
#define TX_STRM_MODE 0x5200
#define RX_STRM_MODE 0x4922
#define INIT_MODE 0x80
// Define CCA types.
#define CLEAR_CHANNEL_ASSESSMENT 0x01
#define ENERGY_DETECT 0x02
// Timer macros.
#define NUMTIMERS 4
#define TIMER1 0
#define TIMER2 1
#define TIMER3 2
#define TIMER4 3
//Default channel
#ifndef MC13192_DEF_CHANNEL
#define MC13192_DEF_CHANNEL 7
#endif
#endif
|
tinyos-io/tinyos-3.x-contrib | kasetsart/tos/chips/atm328/adc/Atm328Adc.h | <reponame>tinyos-io/tinyos-3.x-contrib
/**
* This file is modified from
* <code>tinyos-2.1.0/tos/chips/atm128/adc/Atm128Adc.h</code>
*
* @author
* <NAME> (<EMAIL>)
*/
#ifndef ATM328ADC_H
#define ATM328ADC_H
//================== 8 channel 10-bit ADC ==============================
/* Voltage Reference Settings */
enum {
ATM328_ADC_VREF_OFF = 0, // !< VR += AREF and VR -= GND
ATM328_ADC_VREF_AVCC = 1, // !< VR += AVcc and VR -= GND
ATM328_ADC_VREF_RSVD = 2, // !< Reserved
ATM328_ADC_VREF_1_1 = 3, // !< VR += 1.1V and VR -= GND
};
/* Voltage Reference Settings */
enum {
ATM328_ADC_RIGHT_ADJUST = 0,
ATM328_ADC_LEFT_ADJUST = 1,
};
/* ADC Multiplexer Settings */
enum {
ATM328_ADC_MUX_ADC0 = 0,
ATM328_ADC_MUX_ADC1,
ATM328_ADC_MUX_ADC2,
ATM328_ADC_MUX_ADC3,
ATM328_ADC_MUX_ADC4,
ATM328_ADC_MUX_ADC5,
ATM328_ADC_MUX_ADC6,
ATM328_ADC_MUX_ADC7,
ATM328_ADC_MUX_ADC8,
ATM328_ADC_MUX_1_1 = 14,
ATM328_ADC_MUX_GND,
};
/* ADC Prescaler Settings */
/* Note: each platform must define ATM328_ADC_PRESCALE to the smallest
prescaler which guarantees full A/D precision. */
enum {
ATM328_ADC_PRESCALE_2 = 0,
ATM328_ADC_PRESCALE_2b,
ATM328_ADC_PRESCALE_4,
ATM328_ADC_PRESCALE_8,
ATM328_ADC_PRESCALE_16,
ATM328_ADC_PRESCALE_32,
ATM328_ADC_PRESCALE_64,
ATM328_ADC_PRESCALE_128,
// This special value is used to ask the platform for the prescaler
// which gives full precision.
ATM328_ADC_PRESCALE
};
/* ADC Enable Settings */
enum {
ATM328_ADC_ENABLE_OFF = 0,
ATM328_ADC_ENABLE_ON,
};
/* ADC Start Conversion Settings */
enum {
ATM328_ADC_START_CONVERSION_OFF = 0,
ATM328_ADC_START_CONVERSION_ON,
};
/* ADC Free Running Select Settings */
enum {
ATM328_ADC_FREE_RUNNING_OFF = 0,
ATM328_ADC_FREE_RUNNING_ON,
};
/* ADC Interrupt Flag Settings */
enum {
ATM328_ADC_INT_FLAG_OFF = 0,
ATM328_ADC_INT_FLAG_ON,
};
/* ADC Interrupt Enable Settings */
enum {
ATM328_ADC_INT_ENABLE_OFF = 0,
ATM328_ADC_INT_ENABLE_ON,
};
/* ADC Auto Trigger Sources */
enum {
ATM328_ADC_ATS_FREE_RUN = 0,
ATM328_ADC_ATS_ANALOG_COMPARE,
ATM328_ADC_ATS_EXINT_0,
ATM328_ADC_ATS_TC0_COMP_A,
ATM328_ADC_ATS_TC0_OVF,
ATM328_ADC_ATS_TC1_COMP_B,
ATM328_ADC_ATS_TC1_OVF,
ATM328_ADC_ATS_TC1_CAPTURE,
};
/* ADC Multiplexer Selection Register */
typedef union
{
uint8_t flat;
struct
{
uint8_t mux : 4; //!< Analog Channel and Gain Selection Bits
uint8_t rsvd : 1; //!< Reserved
uint8_t adlar : 1; //!< ADC Left Adjust Result
uint8_t refs : 2; //!< Reference Selection Bits
} bits;
} Atm328_ADMUX_t;
/* ADC Control and Status Register A */
typedef union
{
uint8_t flat;
struct
{
uint8_t adps : 3; //!< ADC Prescaler Select Bits
uint8_t adie : 1; //!< ADC Interrupt Enable
uint8_t adif : 1; //!< ADC Interrupt Flag
uint8_t adate : 1; //!< ADC Auto Trigger Enable
uint8_t adsc : 1; //!< ADC Start Conversion
uint8_t aden : 1; //!< ADC Enable
} bits;
} Atm328_ADCSRA_t;
/* ADC Control and Status Register B */
typedef union
{
uint8_t flat;
struct
{
uint8_t adts : 3; //!< ADC Auto Trigger Source
uint8_t rsvd1 : 3; //!< Reserved
uint8_t adme : 1; //!< Analog Comparator Mux Enable
uint8_t rsvd2 : 1; //!< Reserved
} bits;
} Atm328_ADCSRB_t;
// The resource and client identifier strings for the ADC subsystem
#define UQ_ATM328ADC_RESOURCE "atm328adc.resource"
/* Configuration information */
typedef struct
{
uint8_t channel; //!< Must be one of the ATM328_ADC_MUX_xxx
uint8_t ref_voltage; //!< Must be one of the ATM328_ADC_VREF_xxx values
uint8_t prescaler; //!< Must be one of the ATM328_ADC_PRESCALE_xxx values
} Atm328Adc_config_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | antlab-polimi/dpcm_C/jpegTOS.c | <reponame>tinyos-io/tinyos-3.x-contrib<filename>antlab-polimi/dpcm_C/jpegTOS.c
/*
* 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 <stdio.h>
#include "tinyos_macros.h"
#include "jpeghdr.h"
#include "dctfstBlk.h"
//#include "rleCompress.h"
#include "codeZeros.h"
#include "huffmanCompress.h"
#include "rgb2ycc.h"
#include "quanttables.h"
//#define RLE_ONLY
//int8_t dct_output[320*240];
//uint8_t tmpOut[320*240];
int8_t *dct_output;
uint8_t *tmpOut;
int32_t rgb_ycc_table[RGB_YCC_TABLE_SIZE];
void set_resolution(int width, int height) {
dct_output = malloc(sizeof(int8_t) * width * height);
tmpOut = malloc(sizeof(uint16_t) * width * height);
}
void free_memory() {
free(dct_output);
free(tmpOut);
}
void init()
{
rgb_ycc_init(rgb_ycc_table);
}
void writeOrigFile(int8_t *dct_output, uint32_t dataSize)
{
FILE *fd_tmp1=0;
if ((fd_tmp1 = fopen("orig.huf", "w")) ){
fwrite(dct_output,1,dataSize,fd_tmp1);
fclose(fd_tmp1);
}
else
printf("Can't open orig.huf file for writing\n");
}
uint32_t encodeJpeg(uint8_t *dataIn, uint8_t *dataOut, uint32_t bandwidthLimit,
uint16_t width, uint16_t height, uint8_t
qual, uint8_t bufFix, uint8_t color)
{
uint16_t i,j;
uint32_t idx=0, dataSize=width*height;
uint16_t dcSize = dataSize/64;
code_header_t *header = (code_header_t *)dataOut; //salvo indirizzo inizio file
uint8_t *dct_code_data = &dataOut[CODE_HEADER_SIZE]; //salvo indirizzo inizio dati, successivo all'header
uint8_t tmp0=width>>3, tmp1=height>>3; //divido per otto per calcolare il numero di blocchi
uint16_t tmp2=tmp0*tmp1;
if (bandwidthLimit<(CODE_HEADER_SIZE+dataSize/64))
return 0;
for (i=0; i<tmp0; i++)
for (j=0; j<tmp1; j++)
dctQuantBlock(i, j, tmp2,
dataIn, bufFix, dct_output,
QUANT_TABLE, qual, width);
writeOrigFile(dct_output, dataSize);
header->width=width;
header->height=height;
header->quality=qual;
header->is_color = color;
#ifdef RLE_ONLY
idx=codeDC(dct_output, dct_code_data, dcSize);
idx+=codeZeros(&dct_output[dcSize], &dct_code_data[dcSize], dataSize-dcSize, bandwidthLimit-dcSize);
//idx=RLE_Compress(dct_output, dct_code_data, dataSize);
#else
idx=codeDC(dct_output, tmpOut, dcSize);
idx+=codeZeros(&dct_output[dcSize], &tmpOut[dcSize], dataSize-dcSize, bandwidthLimit-dcSize);
#endif
header->sizeRLE = (uint16_t)idx;
#ifndef RLE_ONLY
idx=Huffman_Compress(tmpOut, dct_code_data,idx);
#endif
header->sizeHUF = (uint16_t)idx;
header->totalSize = idx;
return idx+CODE_HEADER_SIZE;
}
uint32_t encodeColJpeg(uint8_t *dataIn, uint8_t *dataOut, uint32_t bandwidthLimit,
uint16_t width, uint16_t height, uint8_t qual, uint8_t bufFix)
{
init();
rgb_ycc_convert(dataIn,dataIn,rgb_ycc_table,width*3,height);
uint32_t idx=encodeJpeg(dataIn, dataOut, bandwidthLimit, width, height, qual, bufFix,1);
idx+=encodeJpeg(&dataIn[1], &dataOut[idx], bandwidthLimit, width, height, qual, bufFix,1);
idx+=encodeJpeg(&dataIn[2], &dataOut[idx], bandwidthLimit, width, height, qual, bufFix,1);
((code_header_t *)dataOut)->totalSize = idx;
return idx;
}
|
tinyos-io/tinyos-3.x-contrib | nxtmote/tos/chips/at91/i2c/c_lowspeed.h | //
// Date init 14.12.2004
//
// Revision date $Date: 2007/12/18 21:48:12 $
//
// Filename $Workfile:: c_lowspeed.h $
//
// Version $Revision: 1.1 $
//
// Archive $Archive:: /LMS2006/Sys01/Main/Firmware/Source/c_lowspeed $
//
// Platform C
//
#ifndef C_LOWSPEED
#define C_LOWSPEED
#define LOWSPEED_RX_TIMEOUT 100
#define LOWSPEED_COMMUNICATION_SUCCESS 0x01
#define LOWSPEED_COMMUNICATION_ERROR 0xFF
#define SIZE_OF_LSBUFDATA 16
#define NO_OF_LOWSPEED_COM_CH 4
enum
{
LOWSPEED_CHANNEL1,
LOWSPEED_CHANNEL2,
LOWSPEED_CHANNEL3,
LOWSPEED_CHANNEL4
};
enum
{
TIMER_STOPPED,
TIMER_RUNNING
};
typedef struct
{
UBYTE Buf[SIZE_OF_LSBUFDATA];
UBYTE InPtr;
UBYTE OutPtr;
}LSDATA;
typedef struct
{
LSDATA OutputBuf[NO_OF_LOWSPEED_COM_CH];
LSDATA InputBuf[NO_OF_LOWSPEED_COM_CH];
UBYTE RxTimeCnt[NO_OF_LOWSPEED_COM_CH];
UBYTE ErrorCount[NO_OF_LOWSPEED_COM_CH];
UBYTE Tmp;
UBYTE TimerState;
}VARSLOWSPEED;
void cLowSpeedInit();//void* pHeader);
void cLowSpeedCtrl();
void cLowSpeedExit();
//extern const HEADER cLowSpeed;
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/support/sdk/c/blip/lib6lowpan/blip-pc-includes.h | <filename>berkeley/blip-2.0/support/sdk/c/blip/lib6lowpan/blip-pc-includes.h
#ifndef _BLIP_PC_INCLUDES_H_
#define _BLIP_PC_INCLUDES_H_
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#if HAVE_CONFIG_H
#include "config.h"
#endif
#if HAVE_STDINT_H
# include <stdint.h>
#else
# if HAVE_INTTYPES_H
# include <inttypes.h>
# else
# error "no int types found!"
#endif
#endif // int types
#if HAVE_LINUX_IF_TUN_H
# include <linux/if_tun.h>
#else
// # error "TUN device not supported on this platform"
struct tun_pi {
uint32_t af;
};
#endif
#if HAVE_NET_IF_H
// OSX prerequisites
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#if HAVE_NET_ROUTE_H
#include <net/route.h>
#endif
# include <net/if.h> // for IFNAMSIZ
#else
# error "no IFNAMSIZE defined"
#endif
#if HAVE_NETINET_IN_H
# include <netinet/in.h>
#if ! HAVE_IN6_ADDR_S6_ADDR
# define s6_addr16 __u6_addr.__u6_addr16
# endif
#else
# error "no netinet/in.h"
#endif
#if HAVE_ARPA_INET_H
# include <arpa/inet.h>
# include "nwbyte.h"
#else
# error "no htons routines!"
#endif
#endif
|
tinyos-io/tinyos-3.x-contrib | tinybotics/tos/platforms/robostix/RobostixTimer.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.
*
* Copyright (c) 2007 University of Padova
* Copyright (c) 2007 Orebro 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 the copyright holders nor the names of
* their 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 THEIR 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 ROBOSTIXTIMER_H
#define ROBOSTIXTIMER_H
#include <Timer.h>
#include <Atm128Timer.h>
/* Some types for the non-standard rates that robostix timers might be running
at.
*/
typedef struct { } T64khz;
/* TX is the typedef for the rate of timer X,
ROBOSTIX_PRESCALER_X is the prescaler for timer X,
ROBOSTIX_DIVIDER_X_FOR_Y_LOG2 is the number of bits to shift timer X by
to get rate Y,
counter_X_overflow_t is uint16_t if ROBOSTIX_DIVIDER_X_FOR_Y_LOG2 is 0,
uint32_t otherwise.
*/
// default settings
#if MHZ == 16
typedef T64khz TZero;
typedef uint32_t counter_zero_overflow_t;
enum {
ROBOSTIX_PRESCALER_ZERO = ATM128_CLK8_DIVIDE_256,
ROBOSTIX_DIVIDE_ZERO_FOR_MILLI_LOG2 = 6,
};
#else
#error "Unknown clock rate. MHZ must be defined to one of 1, 2, 4, or 8."
#endif
enum {
PLATFORM_MHZ = MHZ
};
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/tos/chips/cc2420_hotmac/hotmac.h | <filename>berkeley/blip-2.0/tos/chips/cc2420_hotmac/hotmac.h
#ifndef HOTMAC_H
#define HOTMAC_H
#include <Ieee154.h>
typedef enum {
S_IDLE = 0,
S_RECEIVE,
S_TRANSMIT,
S_OFF,
} hotmac_state_t;
nx_struct hotmac_beacon {
nx_uint8_t network;
nx_uint16_t period; /* how often our receive checks are */
nx_uint16_t cwl; /* the number of contention slots */
};
struct hotmac_neigh_entry {
ieee154_saddr_t neigh;
uint16_t phase;
uint16_t period;
uint8_t lsn;
// bit fields
uint8_t valid:1;
uint8_t pinned:1; /* possible to evict */
uint8_t lru:4;
};
enum {
HOTMAC_6LOWPAN_NETWORK = 0xff,
// shortest amount to wait after receiving an ACK to a probe before
// transmitting another probe.
// has to be long enough so that any packets sent in response to
// this probe have enough time to finish transmission, about 4ms for
// a 127 byte packet.
// this also determines the window you have to get out a second
// packet, for the streaming optimization
// jiffies
HOTMAC_POSTPROBE_WAIT = 20 << 5,
// the length of a SIFS contention slot, in jiffies.
// this is about 1ms.
HOTMAC_CWIN_SIZE = 0x1F,
HOTMAC_NEIGHBORTABLE_SZ = 4,
// jiffies
HOTMAC_DEFAULT_CHECK_PERIOD = 512L << 5,
// how long to wait for a beacon each time we wake up. this is
// probably also the largest time you want to go between polling the
// channel.
// jiffies
HOTMAC_SEND_TIMEOUT = (HOTMAC_DEFAULT_CHECK_PERIOD * 5) / 2, // (HOTMAC_DEFAULT_CHECK_PERIOD >> 5) + 35,
// how long to wake up before a beacon is scheduled, to turn on the
// radio and load the packet. actual time on a telosb seems to be around 144 jiffies
// jiffies
HOTMAC_WAKEUP_LOAD_TIME = 160, // 45 << 5,
// once awake to send a beacon, if we have to wait more then this
// amount assume we missed the slot we were going for.
// jiffies
HOTMAC_WAKEUP_TOO_LONG = HOTMAC_WAKEUP_LOAD_TIME,
// we'll wake up extra early just to
// make sure we don't miss it due to getting delayed by other tasks,
// drift, or loading the FIFO.
// jiffies
HOTMAC_GUARD_TIME = 100,
//
HOTMAC_DELIVERY_ATTEMPTS = 0,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | diku/common/lib/compression/huffman_whole.h | <filename>diku/common/lib/compression/huffman_whole.h
#define CODESET "../../tools/compression/huffman/huffman_whole_codes.h"
#include "../../tools/compression/huffman/huffman_comp.c"
|
tinyos-io/tinyos-3.x-contrib | eon/tos/lib/tossim/sim_radio.c | <reponame>tinyos-io/tinyos-3.x-contrib
#include <sim_radio.h>
radio_entry_t* connectivity[TOSSIM_MAX_NODES + 1];
radio_entry_t* sim_radio_allocate_link(int mote);
void sim_radio_deallocate_link(radio_entry_t* linkToDelete);
radio_entry_t* sim_radio_first(int src)
{
if (src > TOSSIM_MAX_NODES) {
return connectivity[TOSSIM_MAX_NODES];
}
return connectivity[src];
}
radio_entry_t* sim_radio_next(radio_entry_t* currentLink)
{
return currentLink->next;
}
void sim_radio_add(int src, int dest, int cap, double energy_per_pkt, sim_time_t expires)
{
radio_entry_t* current;
int temp = sim_node();
if (src > TOSSIM_MAX_NODES) {
src = TOSSIM_MAX_NODES;
}
sim_set_node(src);
current = sim_radio_first(src);
while (current != NULL) {
if (current->mote == dest) {
sim_set_node(temp);
break;
}
current = current->next;
}
if (current == NULL) {
current = sim_radio_allocate_link(dest);
current->next = connectivity[src];
connectivity[src] = current;
}
current->mote = dest;
current->cap = cap;
current->energy_per_pkt = energy_per_pkt;
current->expires = expires;
//dbg("Gain", "Adding link from %i to %i with capacity %i and energy/pkt %f uJ (expires %i)\n", src, dest, cap, energy_per_pkt,expires);
sim_set_node(temp);
}
int sim_radio_capacity(int src, int dest)
{
radio_entry_t* current;
int temp = sim_node();
sim_set_node(src);
current = sim_radio_first(src);
while (current != NULL) {
if (current->mote == dest) {
sim_set_node(temp);
if (current->expires <= sim_time())
{
sim_radio_remove(src,dest);
//dbg("Gain", "Link expired from %i to %i\n", src, dest);
return 0;
}
//dbg("Gain", "Getting link from %i to %i with capacity %i\n", src, dest, current->cap);
return current->cap;
}
current = current->next;
}
sim_set_node(temp);
//dbg("Gain", "No link from %i to %i\n", src, dest);
return 0;
}
void sim_radio_set_capacity(int src, int dest, int newcap)
{
radio_entry_t* current;
int temp = sim_node();
sim_set_node(src);
current = sim_radio_first(src);
while (current != NULL) {
if (current->mote == dest) {
sim_set_node(temp);
if (current->expires <= sim_time())
{
sim_radio_remove(src,dest);
//dbg("Gain", "Link expired from %i to %i\n", src, dest);
return;
}
//dbg("Gain", "Setting link from %i to %i to capacity %i\n", src, dest, newcap);
current->cap = newcap;
return;
}
current = current->next;
}
sim_set_node(temp);
//dbg("Gain", "No link from %i to %i\n", src, dest);
return;
}
bool sim_radio_consume_capacity(int src, int dest, int delta)
{
radio_entry_t* current;
int temp = sim_node();
sim_set_node(src);
current = sim_radio_first(src);
while (current != NULL) {
if (current->mote == dest) {
sim_set_node(temp);
if (current->expires <= sim_time())
{
sim_radio_remove(src,dest);
//dbg("Gain", "Link expired from %i to %i\n", src, dest);
return FALSE;
}
//dbg("Gain", "Setting link from %i to %i to capacity %i\n", src, dest, newcap);
if (current->cap < delta) return FALSE;
current->cap -= delta;
if (current->cap == 0)
{
sim_radio_remove(src,dest);
}
return TRUE;
}
current = current->next;
}
sim_set_node(temp);
//dbg("Gain", "No link from %i to %i\n", src, dest);
return FALSE;
}
bool sim_radio_connected(int src, int dest)
{
radio_entry_t* current;
int temp = sim_node();
sim_set_node(src);
current = sim_radio_first(src);
while (current != NULL) {
if (current->mote == dest && current->cap > 0 && current->expires > sim_time()) {
sim_set_node(temp);
return TRUE;
}
current = current->next;
}
sim_set_node(temp);
return FALSE;
}
void sim_radio_remove(int src, int dest)
{
radio_entry_t* current;
radio_entry_t* prevLink;
int temp = sim_node();
if (src > TOSSIM_MAX_NODES) {
src = TOSSIM_MAX_NODES;
}
sim_set_node(src);
current = sim_radio_first(src);
prevLink = NULL;
while (current != NULL) {
radio_entry_t* tmp;
if (current->mote == dest) {
if (prevLink == NULL) {
connectivity[src] = current->next;
}
else {
prevLink->next = current->next;
}
tmp = current->next;
sim_radio_deallocate_link(current);
current = tmp;
}
else {
prevLink = current;
current = current->next;
}
}
sim_set_node(temp);
}
radio_entry_t* sim_radio_allocate_link(int mote) {
radio_entry_t* newLink = (radio_entry_t*)malloc(sizeof(radio_entry_t));
newLink->next = NULL;
newLink->mote = mote;
newLink->cap = 1;
newLink->energy_per_pkt = 0.01;
newLink->expires = 0;
return newLink;
}
void sim_radio_deallocate_link(radio_entry_t* linkToDelete)
{
free(linkToDelete);
}
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/telos/DS2770.h |
//This code is a modified version of code from the Heliomote project
unsigned char
ds2770_init (void)
{
unsigned char presence;
TOSH_SEL_ADC2_IOFUNC ();
TOSH_MAKE_ADC2_INPUT ();
TOSH_SEL_GIO1_IOFUNC ();
TOSH_MAKE_GIO1_OUTPUT ();
TOSH_CLR_GIO1_PIN ();
TOSH_uwait (300); // Keep low for about 600 us
//TOSH_SET_GIO1_PIN();
//TOSH_uwait(100);
//TOSH_CLR_GIO1_PIN();
TOSH_MAKE_GIO1_INPUT (); // Set pin as input
TOSH_uwait (40); // Wait for presence pulse
presence = TOSH_READ_GIO1_PIN (); // Read the bit on pin for presence
TOSH_uwait (250); // Wait for end of timeslot
return !presence; // 1 = presence, 0 = no presence
}
int
readBit ()
// It reads one bit from the one-wire interface */
{
int result;
TOSH_MAKE_GIO1_OUTPUT (); // Set pin as output
TOSH_CLR_GIO1_PIN (); // Set the line low
TOSH_uwait (1); // Hold the line low for at least one us
TOSH_MAKE_GIO1_INPUT (); // Set pin as input
TOSH_uwait (7); // Wait 14 us before reading bit value
result = TOSH_READ_GIO1_PIN (); // Store bit value
TOSH_uwait (50);
return result;
}
void
writeBit (int bit)
// It writes out a bit
{
if (bit)
{
TOSH_MAKE_GIO1_OUTPUT (); // Set pin as output
TOSH_CLR_GIO1_PIN (); // Set the line low
TOSH_uwait (4); // Hold line low for 2 us
TOSH_MAKE_GIO1_INPUT (); // Set pin as input
TOSH_uwait (50); // Write slot is at least 60 us
}
else
{
TOSH_MAKE_GIO1_OUTPUT (); // Set pin as output
TOSH_CLR_GIO1_PIN (); // Set the line low
TOSH_uwait (50); // Hold line low for at least 60 us
TOSH_MAKE_GIO1_INPUT (); // Release the line
TOSH_uwait (8);
}
}
void
writeByte (int hexNum)
// It sends one byte via the one-wire that corresponds to the binary representation
// of hexNum. The variable next is used when the number is broken down into its
// binary code and it holds the current value of the variable. curBit holds the
// value of the bit to be written to the line.
{
int i;
for (i = 0; i < 8; i++) // Convert to binary code
{
writeBit (hexNum & 0x01);
// shift the data byte for the next bit
hexNum >>= 1;
}
}
int
readByte ()
// It reads a byte from the one-wire and stores it in the array byteArray,
// which will contain the information of the one byte read
{
int loop, result = 0;
for (loop = 0; loop < 8; loop++)
{
// shift the result to get it ready for the next bit
result >>= 1;
// if result is one, then set MS bit
if (readBit ())
result |= 0x80;
}
return result;
}
void
skipROM ()
// Skip ROM command, when only one DS2438 is being used on the line
{
writeByte (0xcc); // Request skip ROM to be executed
}
uint8_t
readAddr (uint8_t addr)
{
uint8_t data;
uint8_t p;
p = ds2770_init ();
if (p)
{
skipROM ();
writeByte (0x69);
writeByte (addr);
data = readByte ();
}
else
{
data = 0xeb;
}
return data;
}
void
writeAddr (uint8_t addr, uint8_t val)
{
ds2770_init ();
skipROM ();
writeByte (0x6C);
writeByte (addr);
writeByte (val);
}
void
refresh ()
{
ds2770_init ();
skipROM ();
writeByte (0x63);
}
|
tinyos-io/tinyos-3.x-contrib | blaze/tos/chips/ccxx00_single/Blaze.h | <filename>blaze/tos/chips/ccxx00_single/Blaze.h<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
*/
#ifndef __BLAZE_H__
#define __BLAZE_H__
#ifndef BLAZE_ENABLE_WHILE_LOOP_PRINTF
#define BLAZE_ENABLE_WHILE_LOOP_PRINTF 0
#endif
#ifndef BLAZE_ENABLE_WHILE_LOOP_LEDS
#define BLAZE_ENABLE_WHILE_LOOP_LEDS 0
#endif
#ifndef BLAZE_ENABLE_TIMING_LEDS
#define BLAZE_ENABLE_TIMING_LEDS 0
#endif
#ifndef BLAZE_CSMA_LEDS
#define BLAZE_CSMA_LEDS 0
#endif
#ifndef BLAZE_ENABLE_SPI_WOR_RX_LEDS
#define BLAZE_ENABLE_SPI_WOR_RX_LEDS 0
#endif
#ifndef BLAZE_ENABLE_LPL_LEDS
#define BLAZE_ENABLE_LPL_LEDS 0
#endif
#ifndef BLAZE_ENABLE_CRC_32
#define BLAZE_ENABLE_CRC_32 1
#endif
#ifndef PRINTF_DUTY_CYCLE
#define PRINTF_DUTY_CYCLE 0
#endif
#ifndef PRINTF_ACKS
#define PRINTF_ACKS 0
#endif
typedef uint8_t blaze_status_t;
typedef uint8_t radio_id_t;
/**
* Note that the first 8 bytes of the header are identical to the
* 8 bytes found in blaze_ack_t
*/
typedef nx_struct blaze_header_t {
nxle_uint8_t length;
nxle_uint16_t fcf;
nxle_uint8_t dsn;
nxle_uint16_t dest;
nxle_uint16_t src;
nxle_uint8_t destpan;
nxle_uint8_t type;
} blaze_header_t;
typedef nx_struct blaze_footer_t {
#if BLAZE_ENABLE_CRC_32
nx_uint32_t crc;
#endif
} blaze_footer_t;
typedef nx_struct blaze_metadata_t {
nx_uint8_t rssi;
nx_uint8_t lqi;
nx_uint8_t radio;
nx_uint8_t maxRetries;
nx_uint16_t retryDelay;
nx_uint16_t rxInterval;
} blaze_metadata_t;
/**
* Acknowledgement frame structure.
*/
typedef nx_struct blaze_ack_t {
nxle_uint8_t length;
nxle_uint16_t fcf;
nxle_uint8_t dsn;
nxle_uint16_t dest;
nxle_uint16_t src;
} blaze_ack_t;
enum {
// size of the header not including the length byte
MAC_HEADER_SIZE = sizeof( blaze_header_t ) - 1,
// size of the footer
MAC_FOOTER_SIZE = sizeof( blaze_footer_t ),
// size of the acknowledgement frame, not including the length byte
ACK_FRAME_LENGTH = sizeof( blaze_ack_t ) - 1,
};
enum blaze_cmd_strobe_enums {
BLAZE_SRES = 0x30,
BLAZE_SFSTXON = 0x31,
BLAZE_SXOFF = 0x32,
BLAZE_SCAL = 0x33,
BLAZE_SRX = 0x34,
BLAZE_STX = 0x35,
BLAZE_SIDLE = 0x36,
BLAZE_SWOR = 0x38,
BLAZE_SPWD = 0x39,
BLAZE_SFRX = 0x3A,
BLAZE_SFTX = 0x3B,
BLAZE_SWORRST = 0x3C,
BLAZE_SNOP = 0x3D,
};
enum blaze_addr_enums {
BLAZE_PATABLE = 0x3E,
BLAZE_TXFIFO = 0x3F,
BLAZE_RXFIFO = 0xBF,
};
enum blaze_state_enums{
BLAZE_S_IDLE = 0x00,
BLAZE_S_RX = 0x01,
BLAZE_S_TX = 0x02,
BLAZE_S_FSTXON = 0x03,
BLAZE_S_CALIBRATE = 0x04,
BLAZE_S_SETTLING = 0x05,
BLAZE_S_RXFIFO_OVERFLOW = 0x06,
BLAZE_S_TXFIFO_UNDERFLOW = 0x07,
};
enum blaze_mask_enums {
BLAZE_WRITE = 0x00,
BLAZE_READ = 0x80,
BLAZE_SINGLE = 0x00,
BLAZE_BURST = 0x40,
};
enum blaze_config_reg_addr_enums {
BLAZE_IOCFG2 = 0x00,
BLAZE_IOCFG1 = 0x01,
BLAZE_IOCFG0 = 0x02,
BLAZE_FIFOTHR = 0x03,
BLAZE_SYNC1 = 0x04,
BLAZE_SYNC0 = 0x05,
BLAZE_PKTLEN = 0x06,
BLAZE_PKTCTRL1 = 0x07,
BLAZE_PKTCTRL0 = 0x08,
BLAZE_ADDR = 0x09,
BLAZE_CHANNR = 0x0A,
BLAZE_FSCTRL1 = 0x0B,
BLAZE_FSCTRL0 = 0x0C,
BLAZE_FREQ2 = 0x0D,
BLAZE_FREQ1 = 0x0E,
BLAZE_FREQ0 = 0x0F,
BLAZE_MDMCFG4 = 0x10,
BLAZE_MDMCFG3 = 0x11,
BLAZE_MDMCFG2 = 0x12,
BLAZE_MDMCFG1 = 0x13,
BLAZE_MDMCFG0 = 0x14,
BLAZE_DEVIATN = 0x15,
BLAZE_MCSM2 = 0x16,
BLAZE_MCSM1 = 0x17,
BLAZE_MCSM0 = 0x18,
BLAZE_FOCCFG = 0x19,
BLAZE_BSCFG = 0x1A,
BLAZE_AGCTRL2 = 0x1B,
BLAZE_AGCTRL1 = 0x1C,
BLAZE_AGCTRL0 = 0x1D,
BLAZE_WOREVT1 = 0x1E,
BLAZE_WOREVT0 = 0x1F,
BLAZE_WORCTRL = 0x20,
BLAZE_FREND1 = 0x21,
BLAZE_FREND0 = 0x22,
BLAZE_FSCAL3 = 0x23,
BLAZE_FSCAL2 = 0x24,
BLAZE_FSCAL1 = 0x25,
BLAZE_FSCAL0 = 0x26,
BLAZE_RCCTRL1 = 0x27,
BLAZE_RCCTRL0 = 0x28,
BLAZE_FSTEST = 0x29,
BLAZE_PTEST = 0x2A,
BLAZE_AGCTEST = 0x2B,
BLAZE_TEST2 = 0x2C,
BLAZE_TEST1 = 0x2D,
BLAZE_TEST0 = 0x2E,
BLAZE_PARTNUM = 0x30 | BLAZE_BURST,
BLAZE_VERSION = 0x31 | BLAZE_BURST,
BLAZE_FREQEST = 0x32 | BLAZE_BURST,
BLAZE_LQI = 0x33 | BLAZE_BURST,
BLAZE_RSSI = 0x34 | BLAZE_BURST,
BLAZE_MARCSTATE = 0x35 | BLAZE_BURST,
BLAZE_WORTIME1 = 0x36 | BLAZE_BURST,
BLAZE_WORTIME0 = 0x37 | BLAZE_BURST,
BLAZE_PKSTATUS = 0x38 | BLAZE_BURST,
BLAZE_VCO_VC_DAC = 0x39 | BLAZE_BURST,
BLAZE_TXBYTES = 0x3A | BLAZE_BURST,
BLAZE_RXBYTES = 0x3B | BLAZE_BURST,
};
#ifndef UQ_BLAZE_RADIO
#define UQ_BLAZE_RADIO "Unique_Blaze_Radio"
#endif
#endif
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/platforms/blazehw/hardware.h | #ifndef _H_hardware_h
#define _H_hardware_h
#include "msp430hardware.h"
//#include "MSP430ADC12.h"
//#include "CC2420Const.h"
//#include "AM.h"
// LEDs
TOSH_ASSIGN_PIN(RED_LED, 1, 0);
TOSH_ASSIGN_PIN(GREEN_LED, 1, 1);
TOSH_ASSIGN_PIN(YELLOW_LED, 2, 2);
TOSH_ASSIGN_PIN(BLUE_LED, 2, 3);
// UART pins
TOSH_ASSIGN_PIN(SOMI0, 3, 2);
TOSH_ASSIGN_PIN(SIMO0, 3, 1);
TOSH_ASSIGN_PIN(UCLK0, 3, 3);
TOSH_ASSIGN_PIN(UTXD0, 3, 4);
TOSH_ASSIGN_PIN(URXD0, 3, 5);
TOSH_ASSIGN_PIN(UTXD1, 3, 6);
TOSH_ASSIGN_PIN(URXD1, 3, 7);
TOSH_ASSIGN_PIN(UCLK1, 5, 3);
TOSH_ASSIGN_PIN(SOMI1, 5, 2);
TOSH_ASSIGN_PIN(SIMO1, 5, 1);
// ADC
TOSH_ASSIGN_PIN(ADC0, 6, 0);
TOSH_ASSIGN_PIN(ADC1, 6, 1);
TOSH_ASSIGN_PIN(ADC2, 6, 2);
TOSH_ASSIGN_PIN(ADC3, 6, 3);
// GIO pins
TOSH_ASSIGN_PIN(GIO0, 2, 0);
TOSH_ASSIGN_PIN(GIO1, 2, 1);
TOSH_ASSIGN_PIN(GIO2, 2, 3);
TOSH_ASSIGN_PIN(GIO3, 2, 6);
// FLASH
TOSH_ASSIGN_PIN(FLASH_CS, 4, 4);
TOSH_ASSIGN_PIN(FLASH_HOLD, 4, 7);
// XXX mhh TOSH_ASSIGN_PIN(FLASH_HOLD, 4, 6);
// PROGRAMMING PINS (tri-state)
TOSH_ASSIGN_PIN(PROG_RX, 1, 1);
TOSH_ASSIGN_PIN(PROG_TX, 2, 2);
// need to undef atomic inside header files or nesC ignores the directive
#undef atomic
#endif // _H_hardware_h
|
tinyos-io/tinyos-3.x-contrib | shimmer/apps/BtStream/Shimmer.h | /*
* Copyright (c) 2010, Shimmer Research, Ltd.
* 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 Shimmer Research, Ltd. 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>
* @date November, 2010
*/
#ifndef SHIMMER_H
#define SHIMMER_H
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
};
// Packet Types
enum {
DATA_PACKET = 0x00,
INQUIRY_COMMAND = 0x01,
INQUIRY_RESPONSE = 0x02,
GET_SAMPLING_RATE_COMMAND = 0x03,
SAMPLING_RATE_RESPONSE = 0x04,
SET_SAMPLING_RATE_COMMAND = 0x05,
TOGGLE_LED_COMMAND = 0x06,
START_STREAMING_COMMAND = 0x07,
SET_SENSORS_COMMAND = 0x08,
SET_ACCEL_RANGE_COMMAND = 0x09,
ACCEL_RANGE_RESPONSE = 0x0A,
GET_ACCEL_RANGE_COMMAND = 0x0B,
SET_5V_REGULATOR_COMMAND = 0x0C,
SET_PMUX_COMMAND = 0x0D,
SET_CONFIG_SETUP_BYTE0_COMMAND = 0x0E,
CONFIG_SETUP_BYTE0_RESPONSE = 0x0F,
GET_CONFIG_SETUP_BYTE0_COMMAND = 0x10,
SET_ACCEL_CALIBRATION_COMMAND = 0x11,
ACCEL_CALIBRATION_RESPONSE = 0x12,
GET_ACCEL_CALIBRATION_COMMAND = 0x13,
SET_GYRO_CALIBRATION_COMMAND = 0x14,
GYRO_CALIBRATION_RESPONSE = 0x15,
GET_GYRO_CALIBRATION_COMMAND = 0x16,
SET_MAG_CALIBRATION_COMMAND = 0x17,
MAG_CALIBRATION_RESPONSE = 0x18,
GET_MAG_CALIBRATION_COMMAND = 0x19,
STOP_STREAMING_COMMAND = 0x20,
SET_GSR_RANGE_COMMAND = 0x21,
GSR_RANGE_RESPONSE = 0x22,
GET_GSR_RANGE_COMMAND = 0x23,
GET_SHIMMER_VERSION_COMMAND = 0x24,
SHIMMER_VERSION_RESPONSE = 0x25,
SET_EMG_CALIBRATION_COMMAND = 0x26,
EMG_CALIBRATION_RESPONSE = 0x27,
GET_EMG_CALIBRATION_COMMAND = 0x28,
SET_ECG_CALIBRATION_COMMAND = 0x29,
ECG_CALIBRATION_RESPONSE = 0x2A,
GET_ECG_CALIBRATION_COMMAND = 0x2B,
GET_ALL_CALIBRATION_COMMAND = 0x2C,
ALL_CALIBRATION_RESPONSE = 0x2D,
GET_FW_VERSION_COMMAND = 0x2E,
FW_VERSION_RESPONSE = 0x2F,
SET_BLINK_LED_COMMAND = 0x30,
BLINK_LED_RESPONSE = 0x31,
GET_BLINK_LED_COMMAND = 0x32,
SET_GYRO_TEMP_VREF_COMMAND = 0x33,
SET_BUFFER_SIZE_COMMAND = 0x34,
BUFFER_SIZE_RESPONSE = 0x35,
GET_BUFFER_SIZE_COMMAND = 0x36,
SET_MAG_GAIN_COMMAND = 0x37,
MAG_GAIN_RESPONSE = 0x38,
GET_MAG_GAIN_COMMAND = 0x39,
SET_MAG_SAMPLING_RATE_COMMAND = 0x3A,
MAG_SAMPLING_RATE_RESPONSE = 0x3B,
GET_MAG_SAMPLING_RATE_COMMAND = 0x3C,
ACK_COMMAND_PROCESSED = 0xFF
};
// Maximum number of channels
enum {
MAX_NUM_2_BYTE_CHANNELS = 12, //3xAccel + 3xGyro + 3xMag + 2xAnEx + HR
MAX_NUM_1_BYTE_CHANNELS = 0,
MAX_NUM_CHANNELS = MAX_NUM_2_BYTE_CHANNELS + MAX_NUM_1_BYTE_CHANNELS,
};
// Packet Sizes
enum {
DATA_PACKET_SIZE = 3 + (MAX_NUM_2_BYTE_CHANNELS * 2) + MAX_NUM_1_BYTE_CHANNELS,
RESPONSE_PACKET_SIZE = 76, // biggest possibly required (3 x kinematic + ECG + EMG calibration responses)
MAX_COMMAND_ARG_SIZE = 21 // maximum number of arguments for any command sent to shimmer (calibration data)
};
// Channel contents
enum {
X_ACCEL = 0x00,
Y_ACCEL = 0x01,
Z_ACCEL = 0x02,
X_GYRO = 0x03,
Y_GYRO = 0x04,
Z_GYRO = 0x05,
X_MAG = 0x06,
Y_MAG = 0x07,
Z_MAG = 0x08,
ECG_RA_LL = 0x09,
ECG_LA_LL = 0x0A,
GSR_RAW = 0x0B,
GSR_RES = 0x0C, //GSR resistance (not used in this app)
EMG = 0x0D,
ANEX_A0 = 0x0E,
ANEX_A7 = 0x0F,
STRAIN_HIGH = 0x10,
STRAIN_LOW = 0x11,
HEART_RATE = 0x12
};
// Infomem contents;
enum {
NV_NUM_CONFIG_BYTES = 94
};
enum {
NV_SAMPLING_RATE = 0,
NV_BUFFER_SIZE = 1,
NV_SENSORS0 = 2,
NV_SENSORS1 = 3,
NV_ACCEL_RANGE = 12,
NV_MAG_CONFIG = 13, //upper 4 bits are gain, lower 4 bits are sampling rate
NV_CONFIG_SETUP_BYTE0 = 14,
NV_ACCEL_CALIBRATION = 18,
NV_GYRO_CALIBRATION = 39,
NV_MAG_CALIBRATION = 60,
NV_EMG_CALIBRATION = 81,
NV_ECG_CALIBRATION = 85,
NV_GSR_RANGE = 93
};
//Sensor bitmap
//SENSORS0
enum {
SENSOR_ACCEL = 0x80,
SENSOR_GYRO = 0x40,
SENSOR_MAG = 0x20,
SENSOR_ECG = 0x10,
SENSOR_EMG = 0x08,
SENSOR_GSR = 0x04,
SENSOR_ANEX_A7 = 0x02,
SENSOR_ANEX_A0 = 0x01
};
//SENSORS1
enum {
SENSOR_STRAIN = 0x80,
SENSOR_HEART = 0x40
};
// Config Byte0 bitmap
enum {
CONFIG_5V_REG = 0x80,
CONFIG_PMUX = 0x40,
CONFIG_GYRO_TEMP_VREF = 0x20
};
// BtStream specific extension to range values
enum {
GSR_AUTORANGE = 0x04,
GSR_X4 = 0x05
};
#endif // SHIMMER_H
|
tinyos-io/tinyos-3.x-contrib | rincon/apps/tests/TestLpl/TestInvalidDestination/TestBroadcast.h | <filename>rincon/apps/tests/TestLpl/TestInvalidDestination/TestBroadcast.h<gh_stars>1-10
#ifndef TESTSYNC_H
#define TESTSYNC_H
typedef nx_struct TestBroadcastMsg {
nx_uint8_t count;
} TestBroadcastMsg;
enum {
AM_TESTSYNCMSG = 0x5,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | gems/ttsp/tinyos/apps/profilers/ProfileTsnDrift/Sensors.h | #ifndef SENSORS_H
#define SENSORS_H
enum {
SENSOR_TYPE_PHOTO = 0,
SENSOR_TYPE_TEMP = 1,
SENSOR_TYPE_VOLTAGE = 2,
SENSOR_TYPE_SINE = 3,
SENSOR_NUM_TYPES = 4
};
#endif |
tinyos-io/tinyos-3.x-contrib | eon/apps/server-e/impl/telos/userstructs.h | #ifndef RT_STRUCTS_H_INCLUDED
#define RT_STRUCTS_H_INCLUDED
#include "ServerE.h"
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.