repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
tinyos-io/tinyos-3.x-contrib | dexma/tos/platforms/z1/hardware.h | #ifndef _H_hardware_h
#define _H_hardware_h
#include "msp430hardware.h"
// LEDs
TOSH_ASSIGN_PIN(RED_LED, 5, 4);
TOSH_ASSIGN_PIN(GREEN_LED, 5, 6);
TOSH_ASSIGN_PIN(YELLOW_LED, 5, 5);
// 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);
#endif // _H_hardware_h
|
tinyos-io/tinyos-3.x-contrib | tcd/powertossim-z/tinyos_files/tinyos-2.0.2/tos/lib/tossim/csma.c | <reponame>tinyos-io/tinyos-3.x-contrib
/*
* "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 default TOSSIM CSMA model.
*
* @author <NAME>
* @date Dec 10 2005
*/
#include <csma.h>
Csma::Csma() {}
Csma::~Csma() {}
int Csma::initHigh() {return sim_csma_init_high();}
int Csma::initLow() {return sim_csma_init_low();}
int Csma::high() {return sim_csma_high();}
int Csma::low() {return sim_csma_low();}
int Csma::symbolsPerSec() {return sim_csma_symbols_per_sec();}
int Csma::bitsPerSymbol() {return sim_csma_bits_per_symbol();}
int Csma::preambleLength() {return sim_csma_preamble_length();}
int Csma::exponentBase() {return sim_csma_exponent_base();}
int Csma::maxIterations() {return sim_csma_max_iterations();}
int Csma::minFreeSamples() {return sim_csma_min_free_samples();}
int Csma::rxtxDelay() {return sim_csma_rxtx_delay();}
int Csma::ackTime() {return sim_csma_ack_time();}
void Csma::setInitHigh(int val) {sim_csma_set_init_high(val);}
void Csma::setInitLow(int val) {sim_csma_set_init_low(val);}
void Csma::setHigh(int val) {sim_csma_set_high(val);}
void Csma::setLow(int val) {sim_csma_set_low(val);}
void Csma::setSymbolsPerSec(int val) {sim_csma_set_symbols_per_sec(val);}
void Csma::setBitsBerSymbol(int val) {sim_csma_set_bits_per_symbol(val);}
void Csma::setPreambleLength(int val) {sim_csma_set_preamble_length(val);}
void Csma::setExponentBase(int val) {sim_csma_set_exponent_base(val);}
void Csma::setMaxIterations(int val) {sim_csma_set_max_iterations(val);}
void Csma::setMinFreeSamples(int val) {sim_csma_set_min_free_samples(val);}
void Csma::setRxtxDelay(int val) {sim_csma_set_rxtx_delay(val);}
void Csma::setAckTime(int val); {sim_csma_set_ack_time(val);}
#endif
|
tinyos-io/tinyos-3.x-contrib | diku/mcs51/tos/chips/mcs51/bits/pthreadtypes.h | /*
* We don't need any of this stuff - we just wan't to not load the system one
*/
#ifndef _BITS_PTHREADTYPES_H
#define _BITS_PTHREADTYPES_H 1
#endif /* bits/pthreadtypes.h */
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/support/sdk/c/blip/interface/tun_dev_linux.c | <reponame>tinyos-io/tinyos-3.x-contrib
/*
* "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."
*
*/
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/if_ether.h>
#include <netinet/in.h>
#include <lib6lowpan/lib6lowpan.h>
#include "tun_dev.h"
#include "logging.h"
/*
* This is in linux/include/net/ipv6.h.
* Thanks, net-tools!
*/
struct in6_ifreq {
struct in6_addr ifr6_addr;
__u32 ifr6_prefixlen;
unsigned int ifr6_ifindex;
};
int tun_open(char *dev)
{
struct ifreq ifr;
int fd;
if ((fd = open("/dev/net/tun", O_RDWR)) < 0)
return -1;
memset(&ifr, 0, sizeof(ifr));
/* By default packets are tagged as IPv4. To tag them as IPv6,
* they need to be prefixed by struct tun_pi.
*/
//ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
ifr.ifr_flags = IFF_TUN;
if (*dev)
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
if (ioctl(fd, TUNSETIFF, (void *) &ifr) < 0)
goto failed;
strcpy(dev, ifr.ifr_name);
return fd;
failed:
log_fatal_perror("tun_open");
close(fd);
return -1;
}
int tun_setup(char *dev, ieee154_laddr_t link_address) {
struct in6_ifreq ifr6;
struct ifreq ifr;
int fd;
if ((fd = socket(PF_INET6, SOCK_DGRAM, 0)) < 0)
return -1;
memset(&ifr, 0, sizeof(struct ifreq));
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
/* set the interface up */
if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
log_fatal_perror("SIOCGIFFLAGS");
return -1;
}
ifr.ifr_flags |= IFF_UP;
if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0) {
log_fatal_perror("SIOCSIFFLAGS");
return -1;
}
/* MTU */
ifr.ifr_mtu = 1280;
if (ioctl(fd, SIOCSIFMTU, &ifr) < 0) {
log_fatal_perror("SIOCSIFMTU");
return -1;
}
/* Addresses */
memset(&ifr6, 0, sizeof(struct in6_ifreq));
// memcpy(&ifr6.ifr6_addr, addr, 16);
if (ioctl(fd, SIOGIFINDEX, &ifr) < 0) {
log_fatal_perror("SIOGIFINDEX");
return -1;
}
ifr6.ifr6_ifindex = ifr.ifr_ifindex;
/* don't set the global address */
/* ifr6.ifr6_prefixlen = pfxlen; */
/* if (ioctl(fd, SIOCSIFADDR, &ifr6) < 0) { */
/* log_fatal_perror("SIOCSIFADDR (global)"); */
/* return -1; */
/* } */
/* Just set the lin-local... */
ifr6.ifr6_addr.s6_addr16[0] = htons(0xfe80);
ifr6.ifr6_prefixlen = 64;
memcpy(&ifr6.ifr6_addr.s6_addr[8], link_address.data, 8);
if (ioctl(fd, SIOCSIFADDR, &ifr6) < 0) {
log_fatal_perror("SIOCSIFADDR (local)");
return -1;
}
close(fd);
return 0;
}
int tun_close(int fd, char *dev)
{
return close(fd);
}
/* Read/write frames from TUN device */
int tun_write(int fd, struct ip6_packet *msg) {
uint8_t buf[INET_MTU + sizeof(struct tun_pi)], *packet;
struct tun_pi *pi = (struct tun_pi *)buf;
int length = sizeof(struct ip6_hdr) + sizeof(struct tun_pi);
packet = (uint8_t *)(pi + 1);
if (ntohs(msg->ip6_hdr.ip6_plen) + sizeof(struct ip6_hdr) >= INET_MTU)
return 1;
pi->flags = 0;
pi->proto = htons(ETH_P_IPV6);
memcpy(packet, &msg->ip6_hdr, sizeof(struct ip6_hdr));
packet += sizeof(struct ip6_hdr);
length += iov_read(msg->ip6_data, 0, iov_len(msg->ip6_data), packet);
debug("delivering packet\n");
print_buffer(buf, length);
return write(fd, buf, length);
}
int tun_read(int fd, char *buf, int len)
{
int out;
out = read(fd, buf, sizeof(struct tun_pi) + len);
return out;
}
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/tinyos/fluxhandler.h | <gh_stars>1-10
#ifndef FLUXHANDLER_H_INCLUDED
#define FLUXHANDLER_H_INCLUDED
#include "rt_structs.h"
//#include "MemAlloc.h"
result_t callEdge (uint16_t dest, void *invar, void *outvar);
result_t adjustIntervals();
task void FinishRecoverTask();
int16_t getOutSize (uint16_t nodeid);
result_t handle_error (uint16_t nodeid, uint8_t error);
uint16_t translateIDAll (EdgeIn * e, uint16_t * wt);
void *getInVar(uint16_t nodeid);
void *getOutVar(uint16_t nodeid);
bool *getOutValid(uint16_t nodeid);
void *getOutQueue(uint16_t nodeid, uint8_t slot);
rt_data *getRTData(uint16_t nodeid);
int16_t getSrcWeight(uint16_t srcid);
bool dolocalenqueue (EdgeQueue * q, EdgeIn edge);
uint16_t getNextSession ();
result_t callError (uint16_t nodeid,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;
*/
bool __get_bit_lock_value(uint16_t node_id)
{
int byte_idx, bit_idx;
byte_idx = node_id / 8;
bit_idx = node_id % 8;
return ((__node_locks[byte_idx] >> bit_idx) & 0x01);
}
bool __set_bit_lock_value(uint16_t node_id, bool value)
{
int byte_idx, bit_idx;
uint8_t mask;
byte_idx = node_id / 8;
bit_idx = node_id % 8;
mask = (0x01 << bit_idx);
if (value)
{
__node_locks[byte_idx] = (__node_locks[byte_idx] | mask);
} else {
__node_locks[byte_idx] = (__node_locks[byte_idx] & (~mask));
}
return value;
}
bool __try_node_lock(uint16_t node_id)
{
bool set = FALSE;
atomic {
if (__get_bit_lock_value(node_id) == FALSE)
{
__set_bit_lock_value(node_id,TRUE);
set = TRUE;
}
} //atomic
return set;
}
bool __release_node_lock(uint16_t node_id)
{
atomic {
__set_bit_lock_value(node_id, FALSE);
}
return TRUE;
}
event result_t RTClockTimer.fired()
{
rt_clock += RTCLOCKSEC;
__rtstate.clock = rt_clock;
/*if (rt_clock > (60L * 10L))
{
booted = FALSE;
}*/
return SUCCESS;
}
event result_t EvalTimer.fired()
{
call IEval.reeval_energy_level();
return SUCCESS;
}
event result_t IEval.reeval_done(uint8_t state, double grade)
{
curstate = state;
curgrade = grade;
adjustIntervals();
return SUCCESS;
}
/************************************
*
* EDGE Consumer/Producer functions
*
************************************/
task void
LocalConsumerTask ()
{
uint16_t result;
uint16_t realdest;
uint16_t realweight;
uint16_t delay;
EdgeIn edge;
rt_data *src_data = NULL, *dst_data;
void *soutvar, *dinvar, *doutvar;
delay = FALSE;
result = dequeue (&moteQ, &edge);
if (result == FALSE)
{
localCAlive = FALSE;
return;
}
//translate the edge
realdest = translateIDAll (&edge, &realweight);
if (realdest == NO_NODEID)
{
//translation error
handle_error(edge.src_id, ERR_TRANSLATE);
return;
}
//check to see if it can be advanced to its destination?
if (!__try_node_lock(realdest))
{
//put it back on the queue
if (!dolocalenqueue (&moteQ, edge))
{
//signal a full queue (drop the flow);
if (edge.src)
{
getOutValid(edge.src_id)[edge.idx] = FALSE;
}
handle_error(edge.src_id, ERR_QUEUE);
}
localCAlive = TRUE;
call localQTimer.start (TIMER_ONE_SHOT, QUEUE_DELAY);
return;
}
//we have the lock
//get the runtime data
if (edge.src == FALSE)
{
src_data = getRTData(edge.src_id);
}
dst_data = getRTData(realdest);
if ((edge.src == FALSE && src_data == NULL) || dst_data == NULL)
{
//runtime system/compiler bug.
//very bad.
__release_node_lock(realdest);
if (edge.src)
{
getOutValid(edge.src_id)[edge.idx] = FALSE;
}
handle_error(edge.src_id, ERR_RTDATA);
localCAlive = TRUE;
call localQTimer.start (TIMER_ONE_SHOT, QUEUE_DELAY);
return;
}
if (edge.src == FALSE)
{
//copy runtime data along
memcpy(dst_data, src_data, sizeof(rt_data));
} else {
//initialize runtime data
dst_data->sessionID = getNextSession();
dst_data->weight = getSrcWeight(edge.src_id);
dst_data->minstate = STATE_BASE;
call IEnergyMap.startPath(dst_data->sessionID);
}
//increment the weight according to the translation
dst_data->weight += realweight;
//copy the source "out" to the dest "in"
if (edge.src)
{
soutvar = getOutQueue(edge.src_id, edge.idx);
} else {
soutvar = getOutVar(edge.src_id);
}
dinvar = getInVar(realdest);
doutvar = getOutVar(realdest);
memcpy(dinvar, soutvar, getOutSize(edge.src_id));
if (edge.src)
{
//free up the previously occupied slot
getOutValid(edge.src_id)[edge.idx] = FALSE;
}
//release the src lock
__release_node_lock(edge.src_id);
//NOW WE ACTUALLY CALL THE NODE
call PowerDisable(); //no power management in nodes
result = callEdge(realdest, dinvar, doutvar);
if (result != SUCCESS)
{
call PowerEnable();
handle_error (realdest, result);
} //if
if (isqueueempty (&moteQ))
{
localCAlive = FALSE;
} else {
post LocalConsumerTask ();
}
} //end LocalConsumerTask
event result_t localQTimer.fired ()
{
if (!post LocalConsumerTask ())
{
call localQTimer.start (TIMER_ONE_SHOT, QUEUE_DELAY);
}
return SUCCESS;
}
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
if (__rtstate.save_flag != 0xDEAD)
{
//no data to recover
//assign defaults
__rtstate.batt_reserve = BATTERY_CAPACITY/2;
__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 result_t PageEEPROM.readDone(result_t res)
{
if (res == SUCCESS)
{
rt_clock = __rtstate.clock + RT_SAVE_SEC;
}
post FinishRecoverTask();
return SUCCESS;
}
/*
Runtime data recovery functions
*/
result_t recoverRunTimeData()
{
save_retries = 0;
__rtstate.save_flag = 0;
post ReadStateTask();
//post FinishRecoverTask();
return SUCCESS;
}
event result_t RecoverTimer.fired ()
{
recoverRunTimeData();
return SUCCESS;
}
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 result_t SaveTimer.fired ()
{
//Save runtime data
__rtstate.save_flag = 0xDEAD;
save_retries = 0;
//post EraseTask();
return SUCCESS;
}
event result_t PageEEPROM.writeDone(result_t res)
{
if (res == SUCCESS)
{
save_retries = 0;
post FlushPageTask();
}
else if (check_retry())
{
post SaveTask();
}
return (SUCCESS);
}
event result_t PageEEPROM.flushDone(result_t res)
{
//We made it! Yeah!
return (SUCCESS);
}
event result_t PageEEPROM.eraseDone(result_t res)
{
if (res == SUCCESS)
{
post SaveTask();
} else if (check_retry())
{
post EraseTask();
}
return (SUCCESS);
}
event result_t PageEEPROM.syncDone(result_t result)
{
return (SUCCESS);
}
event result_t PageEEPROM.computeCrcDone(result_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;
//TODO: figure out if this is necessary.
atomic
{
result = enqueue (q, edge);
if (result && localCAlive == FALSE)
{
localCAlive = TRUE;
post LocalConsumerTask ();
}
} //atomic
return result;
}
#ifdef RUNTIME_TEST
event result_t SendMsg.sendDone(TOS_MsgPtr msg, result_t success)
{
return SUCCESS;
}
#endif
/********************************
* AUX functions
********************************/
uint16_t
getNextSession ()
{
uint16_t nextid;
atomic
{
nextid = session_id;
session_id++;
}
return nextid;
}
result_t handle_exit (uint16_t nodeid)
{
result_t res;
rt_data *pdata = getRTData(nodeid);
__release_node_lock(nodeid);
res = call IEnergyMap.endPath(pdata->sessionID, 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 result_t DummyPathDone.done(uint16_t pathid, uint32_t cost, uint8_t prob, uint8_t srcprob)
{
return SUCCESS;
}
result_t
handle_error (uint16_t nodeid, uint8_t error)
{
//add weight
rt_data *pdata = getRTData(nodeid);
pdata->weight += getErrorWeight (nodeid);
/*if (error == ERR_NOMEMORY)
{
}
if (error == ERR_QUEUE)
{
}*/
//call the correct error handler
return callError (nodeid, error);
}
//CODE FOR HANDLING EDGES BETWEEN NODES
result_t handle_edge (uint16_t srcid, uint16_t dstid, uint16_t edgewt)
{
EdgeIn newedge;
rt_data *pdata;
newedge.src_id = srcid;
newedge.dst_id = dstid;
newedge.src = FALSE; //mark it as not coming from a source
pdata = getRTData(srcid);
if (pdata == NULL)
{
return handle_error(srcid, ERR_SRC);
}
//add this edges weight---further translation will come when it is advanced to the next edge
pdata->weight += edgewt;
if (!dolocalenqueue (&moteQ, newedge))
{
//signal a full queue (drop the flow);
handle_error(srcid, ERR_QUEUE);
return FAIL;
}
return SUCCESS;
}
//CODE FOR HANDLING EDGES FROM SOURCES TO NODES
result_t handle_src_edge (uint16_t srcid, uint16_t dstid)
{
EdgeIn newedge;
bool *out_valid;
int i, slot = -1;
void *outbuf, *queuebuf;
//see if there is an open queue slot
out_valid = getOutValid(srcid);
atomic
{
for (i=0; i < SRC_QUEUE_SIZE; i++)
{
if (out_valid[i] == FALSE)
{
out_valid[i] = TRUE;
slot = i;
break;
}
}
}//atomic
if (slot == -1)
{
//queue full
return FAIL;
}
//copy data into queue
outbuf = getOutVar(srcid);
queuebuf = getOutQueue(srcid,slot);
memcpy(queuebuf, outbuf, getOutSize(srcid));
//put it on the scheduling queue
newedge.src_id = srcid;
newedge.dst_id = dstid;
newedge.src = TRUE; //mark it as coming from a source
newedge.idx = slot;
if (!dolocalenqueue (&moteQ, newedge))
{
//signal a full queue (drop the flow);
handle_error(srcid, ERR_QUEUE);
return FAIL;
}
return SUCCESS;
}
/*
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 | intelmote2/apps/cameraMultiHop/c/get_jpg.c | #include <time.h>
#include "camera_cmd.h"
void callback(int percentage, char* filename){
//((part_idx*100)/max_row)
printf("\b\b\b\b\b%4d%%",percentage);
fflush(stdout);
}
int main(int argc, char **argv)
{
if (argc != 3 && argc != 4)
{
fprintf(stderr,
"Usage: %s <ip_port> <mote_id> [<img_type>]\n\t where img_type: 2=bw_jpg(default) 3=col_jpg 0=bw_raw 1=col_raw",
argv[0]);
exit(2);
}
int port = atoi(argv[1]);
printf("connecting to serialforwarder: localhost:%d\n",port);
comm_init("localhost", port);
int node_id = atoi(argv[2]);
int img_type = 2;
if (argc==4)
img_type=atoi(argv[3]);
char filename[1024];
int ret=0;
sprintf(filename,"./test%d",(int)time(NULL));
printf("sending img request to node %d: ",node_id);
printf("%d\n",send_img_cmd(node_id, img_type));
printf("img: 0%%");
ret = receive_img(node_id, 0, filename, &callback);
printf("\n");
if (ret==-1)
printf("no pkts received!\n");
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | ethz/snpk/apps/Harvester/Harvester.h | /* Copyright (c) 2007 ETH Zurich.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
* OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* For additional information see http://www.btnode.ethz.ch/
*
* $Id: Harvester.h,v 1.14 2008/03/03 14:19:06 rlim Exp $
*
*/
/**
* @author <NAME>
*/
#ifndef HARVESTER_H
#define HARVESTER_H
#include <AM.h>
enum {
/* Number of readings per message. If you increase this, you may have to
increase the message_t size. */
// NREADINGS = 1,
/* Default sampling period. */
AM_HARVESTERSENSOR = 0x93,
INT_SENSOR = 30000,
AM_HARVESTERTOPOLOGY = 0x94,
INT_TOPOLOGY = 62000UL, // milliseconds
AM_HARVESTERSTATUS = 0x95,
INT_STATUS = 0,
};
typedef nx_struct harvesterSensor {
nx_uint8_t dsn; /* serial number */
nx_uint16_t id; /* Mote id of sending mote. */
nx_uint16_t temp_internal; /* raw value of the on-board Sensirion temperature sensor */
nx_uint16_t temp_external; /* raw value of the external Sensirion temperature sensor */
nx_uint16_t hum_internal; /* raw value of the on-board Sensirion humidity sensor */
nx_uint16_t hum_external; /* raw value of the external Sensirion humidity sensor */
nx_uint16_t voltage; /* voltage level */
nx_uint16_t light1; /* value from Hamatsu S1087 light sensor */
nx_uint16_t light2; /* value from Hamatsu S1087-01 light sensor */
} harvester_sensor_t;
typedef nx_struct harvesterTopology {
nx_uint8_t dsn; /* serial number */
nx_uint16_t id; /* Mote id of sending mote. */
nx_am_addr_t parent; /* id of parent node (treerouting) */
nx_uint16_t parent_etx; /* estimated transmissions to parent */
nx_am_addr_t neighbour_id[5]; /* ids of 5 best neighbours */
} harvester_topology_t;
typedef nx_struct harvesterNodeStatus {
nx_uint8_t dsn; /* serial number */
nx_uint16_t id; /* Mote id of sending mote. */
nx_uint32_t prog_version; /* program version e.g. IDENT_TIMESTAMP */
} harvester_status_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/chips/msp430/selfdestruct/SelfDestruct.h |
#ifndef SELFDESTRUCT_H
#define SELFDESTRUCT_H
#endif
|
tinyos-io/tinyos-3.x-contrib | wustl/upma/apps/tests/TestSCP/TestMsg.h | #ifndef __TESTMSG_H
#define __TESTMSG_H
typedef nx_struct TestMsg
{
nx_uint8_t payload[5];
} TestMsg;
enum { AM_TESTMSG = 101 };
#endif /* __TESTMSG_H */
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/lib/string/TinyosString.h | <gh_stars>1-10
/**
* @author <NAME>
*/
#ifndef TINYOS_STRING_H
#define TINYOS_STRING_H
#ifndef DEFAULT_STRING_LENGTH
#define DEFAULT_STRING_LENGTH 100 // max should be 135 + 2 byte length + 2 byte crc on rx
#endif
typedef struct string_t {
uint8_t length;
uint8_t data[DEFAULT_STRING_LENGTH];
} string_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/telos/fluxmarshal.h | <reponame>tinyos-io/tinyos-3.x-contrib<filename>eon/eon/src/runtime/telos/fluxmarshal.h
#ifndef FLUXMARSHAL_H_INCLUDED
#define FLUXMARSHAL_H_INCLUDED
#include "../nodes.h"
#include "../usermarshal.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
#define MARSH_DONE 5
uint8_t encode_int32_t (uint16_t connid, int32_t data);
uint8_t encode_uint32_t (uint16_t connid, uint32_t data);
uint8_t encode_int16_t (uint16_t connid, int16_t data);
uint8_t encode_uint16_t (uint16_t connid, uint16_t data);
uint8_t encode_int8_t (uint16_t connid, int8_t data);
uint8_t encode_uint8_t (uint16_t connid, uint8_t data);
uint8_t encode_bool (uint16_t connid, bool data);
/******************************
*Encode functions
**********************************/
uint8_t
enc_return (result_t result, uint16_t bytes)
{
if (result == FAIL)
{
return MARSH_ERR;
}
if (bytes == 0)
{
return MARSH_FULL;
}
return MARSH_OK;
}
uint8_t
encode_start (uint16_t connid, uint16_t nodeid)
{
uint8_t buffer[3];
uint16_t bytes;
result_t result;
if (nodeid >= NUMNODES)
{
return MARSH_ERR;
}
buffer[0] = TYPE_START;
buffer[1] = nodeid >> 8;
buffer[2] = nodeid & 0xFF;
result =
call RemoteWrite.write (connid, buffer, sizeof (nodeid) + 1, &bytes);
return enc_return (result, bytes);
}
uint8_t
encode_session (uint16_t connid, rt_data _pdata)
{
result_t result;
result = encode_uint16_t (connid, _pdata.sessionID);
if (result != MARSH_OK)
return result;
result = encode_uint32_t (connid, _pdata.starttime);
if (result != MARSH_OK)
return result;
result = encode_uint16_t (connid, _pdata.weight);
if (result != MARSH_OK)
return result;
result = encode_uint8_t (connid, _pdata.minstate);
if (result != MARSH_OK)
return result;
result = encode_bool (connid, _pdata.wake);
if (result != MARSH_OK)
return result;
return MARSH_OK;
}
uint8_t
encode_end (uint16_t connid, uint16_t nodeid)
{
uint8_t buffer[3];
uint16_t bytes;
result_t result;
if (nodeid >= NUMNODES)
{
return MARSH_ERR;
}
buffer[0] = TYPE_END;
buffer[1] = nodeid >> 8;
buffer[2] = nodeid & 0xFF;
result = call RemoteWrite.write (connid, buffer, sizeof (buffer), &bytes);
return enc_return (result, bytes);
}
uint8_t
encode_uint8_t (uint16_t connid, uint8_t data)
{
uint8_t buffer[2];
uint16_t bytes;
result_t result;
buffer[0] = TYPE_UINT8;
buffer[1] = data;
result = call RemoteWrite.write (connid, buffer, sizeof (buffer), &bytes);
return enc_return (result, bytes);
}
uint8_t
encode_uint16_t (uint16_t connid, uint16_t data)
{
uint8_t buffer[3];
uint16_t bytes;
result_t result;
buffer[0] = TYPE_UINT16;
buffer[1] = data >> 8;
buffer[2] = data & 0xFF;
result = call RemoteWrite.write (connid, buffer, sizeof (buffer), &bytes);
return enc_return (result, bytes);
}
uint8_t
encode_uint32_t (uint16_t connid, uint32_t data)
{
uint8_t buffer[5];
uint16_t bytes;
result_t result;
buffer[0] = TYPE_UINT32;
buffer[1] = (data >> 24) & 0xFF;
buffer[2] = (data >> 16) & 0xFF;
buffer[3] = (data >> 8) & 0xFF;
buffer[4] = data & 0xFF;
result = call RemoteWrite.write (connid, buffer, sizeof (buffer), &bytes);
return enc_return (result, bytes);
}
uint8_t
encode_int8_t (uint16_t connid, int8_t data)
{
uint8_t buffer[2];
uint16_t bytes;
result_t result;
buffer[0] = TYPE_INT8;
buffer[1] = data;
result = call RemoteWrite.write (connid, buffer, sizeof (buffer), &bytes);
return enc_return (result, bytes);
}
uint8_t
encode_int16_t (uint16_t connid, int16_t data)
{
uint8_t buffer[3];
uint16_t bytes;
result_t result;
buffer[0] = TYPE_INT16;
buffer[1] = data >> 8;
buffer[2] = data & 0xFF;
result = call RemoteWrite.write (connid, buffer, sizeof (buffer), &bytes);
return enc_return (result, bytes);
}
uint8_t
encode_int32_t (uint16_t connid, int32_t data)
{
uint8_t buffer[5];
uint16_t bytes;
result_t result;
buffer[0] = TYPE_INT32;
buffer[1] = (data >> 24) & 0xFF;
buffer[2] = (data >> 16) & 0xFF;
buffer[3] = (data >> 8) & 0xFF;
buffer[4] = data & 0xFF;
result = call RemoteWrite.write (connid, buffer, sizeof (buffer), &bytes);
return enc_return (result, bytes);
}
uint8_t
encode_int (uint16_t connid, int data)
{
return encode_int16_t (connid, (int16_t) data);
}
uint8_t
encode_char (uint16_t connid, char data)
{
return encode_int8_t (connid, (int8_t) data);
}
uint8_t
encode_bool (uint16_t connid, bool data)
{
return encode_int8_t (connid, (bool) data);
}
uint8_t
encode_request_t (uint16_t connid, request_t data)
{
return MARSH_OK;
}
/***************************
Decode
***************************/
uint8_t
decode_start (uint16_t connid, uint16_t * nodeid)
{
uint8_t buffer[3];
uint16_t bytes;
result_t result;
result = call RemoteRead.read (connid, buffer, sizeof (buffer), &bytes);
if (result == FAIL)
return MARSH_ERR;
if (bytes == 0)
return MARSH_WAIT;
if (buffer[0] != TYPE_START)
return MARSH_TYPE;
*nodeid = (buffer[1] << 8) | buffer[2];
return MARSH_OK;
}
uint8_t
decode_uint8_t (uint16_t connid, uint8_t * data)
{
uint8_t buffer[2];
uint16_t bytes;
result_t result;
result = call RemoteRead.read (connid, buffer, sizeof (buffer), &bytes);
if (result == FAIL)
return MARSH_ERR;
if (bytes == 0)
return MARSH_WAIT;
if (buffer[0] != TYPE_UINT8)
return MARSH_TYPE;
*data = buffer[1];
return MARSH_OK;
}
uint8_t
decode_uint16_t (uint16_t connid, uint16_t * data)
{
uint8_t buffer[3];
uint16_t bytes;
result_t result;
result = call RemoteRead.read (connid, buffer, sizeof (buffer), &bytes);
if (result == FAIL)
return MARSH_ERR;
if (bytes == 0)
return MARSH_WAIT;
if (buffer[0] != TYPE_UINT16)
return MARSH_TYPE;
*data = (buffer[1] << 8) | buffer[2];
return MARSH_OK;
}
uint8_t
decode_uint32_t (uint16_t connid, uint32_t * data)
{
uint8_t buffer[5];
uint16_t bytes;
result_t result;
uint32_t values[4];
result = call RemoteRead.read (connid, buffer, sizeof (buffer), &bytes);
if (result == FAIL)
return MARSH_ERR;
if (bytes == 0)
return MARSH_WAIT;
if (buffer[0] != TYPE_UINT32)
return MARSH_TYPE;
values[0] = buffer[1];
values[1] = buffer[2];
values[2] = buffer[3];
values[3] = buffer[4];
*data =
(values[1] << 24) | (values[2] << 16) | (values[3] << 8) | values[4];
return MARSH_OK;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | wsu/WakeNet/tos/lib/net/ctp/CtpForwardingEngine.h | #ifndef FORWARDING_ENGINE_H
#define FORWARDING_ENGINE_H
/*
* Copyright (c) 2006 Stanford University.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
* - Neither the name of the Stanford University nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STANFORD
* UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <AM.h>
#include <message.h>
/**
* Author: <NAME>
* Author: <NAME>
* Author: <NAME>
* Author: <NAME>
*/
/*
* These timings are in milliseconds, and are used by
* ForwardingEngineP. Each pair of values represents a range of
* [OFFSET - (OFFSET + WINDOW)]. The ForwardingEngine uses these
* values to determine when to send the next packet after an
* event. FAIL refers to a send fail (an error from the radio below),
* NOACK refers to the previous packet not being acknowledged,
* OK refers to an acknowledged packet, and LOOPY refers to when
* a loop is detected.
*
* These timings are defined in terms of packet times. Currently,
* two values are defined: for CC2420-based platforms (4ms) and
* all other platfoms (32ms).
*/
enum {
#if PLATFORM_MICAZ || PLATFORM_TELOSA || PLATFORM_TELOSB || PLATFORM_TMOTE || PLATFORM_INTELMOTE2 || PLATFORM_SHIMMER || PLATFORM_IRIS
FORWARD_PACKET_TIME = 7,
#else
FORWARD_PACKET_TIME = 32,
#endif
};
enum {
SENDDONE_OK_OFFSET = FORWARD_PACKET_TIME,
SENDDONE_OK_WINDOW = FORWARD_PACKET_TIME,
SENDDONE_NOACK_OFFSET = FORWARD_PACKET_TIME,
SENDDONE_NOACK_WINDOW = FORWARD_PACKET_TIME,
SENDDONE_FAIL_OFFSET = FORWARD_PACKET_TIME << 2,
SENDDONE_FAIL_WINDOW = SENDDONE_FAIL_OFFSET,
LOOPY_OFFSET = FORWARD_PACKET_TIME << 2,
LOOPY_WINDOW = LOOPY_OFFSET,
CONGESTED_WAIT_OFFSET = FORWARD_PACKET_TIME << 2,
CONGESTED_WAIT_WINDOW = CONGESTED_WAIT_OFFSET,
NO_ROUTE_RETRY = 10000
};
/*
* The number of times the ForwardingEngine will try to
* transmit a packet before giving up if the link layer
* supports acknowledgments. If the link layer does
* not support acknowledgments it sends the packet once.
*/
enum {
MAX_RETRIES = 30
};
/*
* The network header that the ForwardingEngine introduces.
* This header will change for the TinyOS 2.0 full release
* (it needs several optimizations).
*/
typedef nx_struct {
nx_uint8_t control;
nx_am_addr_t origin;
nx_uint8_t seqno;
nx_uint8_t collectid;
nx_uint16_t gradient;
} network_header_t;
/*
* An element in the ForwardingEngine send queue.
* The client field keeps track of which send client
* submitted the packet or if the packet is being forwarded
* from another node (client == 255). Retries keeps track
* of how many times the packet has been transmitted.
*/
typedef struct {
message_t * ONE_NOK msg;
uint8_t client;
uint8_t retries;
} fe_queue_entry_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | diku/freescale/tos/platforms/dig528/include/ctype.h | /** Dummy header to avoid inclusion of the standard library header **/
#ifndef _CTYPE_H_
#define NULL 0
#define _CTYPE_H_
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/descriptors.c | <filename>nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/descriptors.c
/*
* Parses descriptors
*
* Copyright (c) 2001 <NAME> <<EMAIL>>
*
* This library is covered by the LGPL, read LICENSE for details.
*/
#include <stdio.h>
#include <string.h>
#include "usbi.h"
int usb_get_descriptor_by_endpoint(usb_dev_handle *udev, int ep,
unsigned char type, unsigned char index, void *buf, int size)
{
memset(buf, 0, size);
return usb_control_msg(udev, ep | USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
(type << 8) + index, 0, buf, size, 1000);
}
int usb_get_descriptor(usb_dev_handle *udev, unsigned char type,
unsigned char index, void *buf, int size)
{
memset(buf, 0, size);
return usb_control_msg(udev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
(type << 8) + index, 0, buf, size, 1000);
}
int usb_parse_descriptor(unsigned char *source, char *description, void *dest)
{
unsigned char *sp = source, *dp = dest;
uint16_t w;
uint32_t d;
char *cp;
for (cp = description; *cp; cp++) {
switch (*cp) {
case 'b': /* 8-bit byte */
*dp++ = *sp++;
break;
case 'w': /* 16-bit word, convert from little endian to CPU */
w = (sp[1] << 8) | sp[0]; sp += 2;
//dp += ((unsigned long)dp & 1); /* Align to word boundary */
*((uint16_t *)dp) = w; dp += 2;
break;
case 'd': /* 32-bit dword, convert from little endian to CPU */
d = (sp[3] << 24) | (sp[2] << 16) | (sp[1] << 8) | sp[0]; sp += 4;
//dp += ((unsigned long)dp & 2); /* Align to dword boundary */
*((uint32_t *)dp) = d; dp += 4;
break;
/* These two characters are undocumented and just a hack for Linux */
case 'W': /* 16-bit word, keep CPU endianess */
//dp += ((unsigned long)dp & 1); /* Align to word boundary */
memcpy(dp, sp, 2); sp += 2; dp += 2;
break;
case 'D': /* 32-bit dword, keep CPU endianess */
//dp += ((unsigned long)dp & 2); /* Align to dword boundary */
memcpy(dp, sp, 4); sp += 4; dp += 4;
break;
}
}
return (int)(sp - source);
}
/*
* This code looks surprisingly similar to the code I wrote for the Linux
* kernel. It's not a coincidence :)
*/
static int usb_parse_endpoint(struct usb_endpoint_descriptor *endpoint, unsigned char *buffer, int size)
{
struct usb_descriptor_header header;
unsigned char *begin;
int parsed = 0, len, numskipped;
usb_parse_descriptor(buffer, "bb", &header);
/* Everything should be fine being passed into here, but we sanity */
/* check JIC */
if (header.bLength > size) {
if (usb_debug >= 1)
fprintf(stderr, "ran out of descriptors parsing\n");
return -1;
}
if (header.bDescriptorType != USB_DT_ENDPOINT) {
if (usb_debug >= 2)
fprintf(stderr, "unexpected descriptor 0x%X, expecting endpoint descriptor, type 0x%X\n",
header.bDescriptorType, USB_DT_ENDPOINT);
return parsed;
}
if (header.bLength >= ENDPOINT_AUDIO_DESC_LENGTH)
usb_parse_descriptor(buffer, "bbbbwbbb", endpoint);
else if (header.bLength >= ENDPOINT_DESC_LENGTH)
usb_parse_descriptor(buffer, "bbbbwb", endpoint);
buffer += header.bLength;
size -= header.bLength;
parsed += header.bLength;
/* Skip over the rest of the Class Specific or Vendor Specific */
/* descriptors */
begin = buffer;
numskipped = 0;
while (size >= DESC_HEADER_LENGTH) {
usb_parse_descriptor(buffer, "bb", &header);
if (header.bLength < 2) {
if (usb_debug >= 1)
fprintf(stderr, "invalid descriptor length of %d\n", header.bLength);
return -1;
}
/* If we find another "proper" descriptor then we're done */
if ((header.bDescriptorType == USB_DT_ENDPOINT) ||
(header.bDescriptorType == USB_DT_INTERFACE) ||
(header.bDescriptorType == USB_DT_CONFIG) ||
(header.bDescriptorType == USB_DT_DEVICE))
break;
if (usb_debug >= 1)
fprintf(stderr, "skipping descriptor 0x%X\n", header.bDescriptorType);
numskipped++;
buffer += header.bLength;
size -= header.bLength;
parsed += header.bLength;
}
if (numskipped && usb_debug >= 2)
fprintf(stderr, "skipped %d class/vendor specific endpoint descriptors\n", numskipped);
/* Copy any unknown descriptors into a storage area for drivers */
/* to later parse */
len = (int)(buffer - begin);
if (!len) {
endpoint->extra = NULL;
endpoint->extralen = 0;
return parsed;
}
endpoint->extra = malloc(len);
if (!endpoint->extra) {
if (usb_debug >= 1)
fprintf(stderr, "couldn't allocate memory for endpoint extra descriptors\n");
endpoint->extralen = 0;
return parsed;
}
memcpy(endpoint->extra, begin, len);
endpoint->extralen = len;
return parsed;
}
static int usb_parse_interface(struct usb_interface *interface,
unsigned char *buffer, int size)
{
int i, len, numskipped, retval, parsed = 0;
struct usb_descriptor_header header;
struct usb_interface_descriptor *ifp;
unsigned char *begin;
interface->num_altsetting = 0;
while (size >= INTERFACE_DESC_LENGTH) {
interface->altsetting = realloc(interface->altsetting, sizeof(struct usb_interface_descriptor) * (interface->num_altsetting + 1));
if (!interface->altsetting) {
if (usb_debug >= 1)
fprintf(stderr, "couldn't malloc interface->altsetting\n");
return -1;
}
ifp = interface->altsetting + interface->num_altsetting;
interface->num_altsetting++;
usb_parse_descriptor(buffer, "bbbbbbbbb", ifp);
/* Skip over the interface */
buffer += ifp->bLength;
parsed += ifp->bLength;
size -= ifp->bLength;
begin = buffer;
numskipped = 0;
/* Skip over any interface, class or vendor descriptors */
while (size >= DESC_HEADER_LENGTH) {
usb_parse_descriptor(buffer, "bb", &header);
if (header.bLength < 2) {
if (usb_debug >= 1)
fprintf(stderr, "invalid descriptor length of %d\n", header.bLength);
return -1;
}
/* If we find another "proper" descriptor then we're done */
if ((header.bDescriptorType == USB_DT_INTERFACE) ||
(header.bDescriptorType == USB_DT_ENDPOINT) ||
(header.bDescriptorType == USB_DT_CONFIG) ||
(header.bDescriptorType == USB_DT_DEVICE))
break;
numskipped++;
buffer += header.bLength;
parsed += header.bLength;
size -= header.bLength;
}
if (numskipped && usb_debug >= 2)
fprintf(stderr, "skipped %d class/vendor specific interface descriptors\n", numskipped);
/* Copy any unknown descriptors into a storage area for */
/* drivers to later parse */
len = (int)(buffer - begin);
if (!len) {
ifp->extra = NULL;
ifp->extralen = 0;
} else {
ifp->extra = malloc(len);
if (!ifp->extra) {
if (usb_debug >= 1)
fprintf(stderr, "couldn't allocate memory for interface extra descriptors\n");
ifp->extralen = 0;
return -1;
}
memcpy(ifp->extra, begin, len);
ifp->extralen = len;
}
/* Did we hit an unexpected descriptor? */
usb_parse_descriptor(buffer, "bb", &header);
if ((size >= DESC_HEADER_LENGTH) &&
((header.bDescriptorType == USB_DT_CONFIG) ||
(header.bDescriptorType == USB_DT_DEVICE)))
return parsed;
if (ifp->bNumEndpoints > USB_MAXENDPOINTS) {
if (usb_debug >= 1)
fprintf(stderr, "too many endpoints\n");
return -1;
}
if (ifp->bNumEndpoints > 0) {
ifp->endpoint = (struct usb_endpoint_descriptor *)
malloc(ifp->bNumEndpoints *
sizeof(struct usb_endpoint_descriptor));
if (!ifp->endpoint) {
if (usb_debug >= 1)
fprintf(stderr, "couldn't allocate memory for ifp->endpoint\n");
return -1;
}
memset(ifp->endpoint, 0, ifp->bNumEndpoints *
sizeof(struct usb_endpoint_descriptor));
for (i = 0; i < ifp->bNumEndpoints; i++) {
usb_parse_descriptor(buffer, "bb", &header);
if (header.bLength > size) {
if (usb_debug >= 1)
fprintf(stderr, "ran out of descriptors parsing\n");
return -1;
}
retval = usb_parse_endpoint(ifp->endpoint + i, buffer, size);
if (retval < 0)
return retval;
buffer += retval;
parsed += retval;
size -= retval;
}
} else
ifp->endpoint = NULL;
/* We check to see if it's an alternate to this one */
ifp = (struct usb_interface_descriptor *)buffer;
if (size < USB_DT_INTERFACE_SIZE ||
ifp->bDescriptorType != USB_DT_INTERFACE ||
!ifp->bAlternateSetting)
return parsed;
}
return parsed;
}
int usb_parse_configuration(struct usb_config_descriptor *config,
unsigned char *buffer)
{
int i, retval, size;
struct usb_descriptor_header header;
usb_parse_descriptor(buffer, "bbwbbbbb", config);
size = config->wTotalLength;
if (config->bNumInterfaces > USB_MAXINTERFACES) {
if (usb_debug >= 1)
fprintf(stderr, "too many interfaces\n");
return -1;
}
config->interface = (struct usb_interface *)
malloc(config->bNumInterfaces *
sizeof(struct usb_interface));
if (!config->interface) {
if (usb_debug >= 1)
fprintf(stderr, "out of memory\n");
return -1;
}
memset(config->interface, 0, config->bNumInterfaces * sizeof(struct usb_interface));
buffer += config->bLength;
size -= config->bLength;
config->extra = NULL;
config->extralen = 0;
for (i = 0; i < config->bNumInterfaces; i++) {
int numskipped, len;
unsigned char *begin;
/* Skip over the rest of the Class Specific or Vendor */
/* Specific descriptors */
begin = buffer;
numskipped = 0;
while (size >= DESC_HEADER_LENGTH) {
usb_parse_descriptor(buffer, "bb", &header);
if ((header.bLength > size) || (header.bLength < DESC_HEADER_LENGTH)) {
if (usb_debug >= 1)
fprintf(stderr, "invalid descriptor length of %d\n", header.bLength);
return -1;
}
/* If we find another "proper" descriptor then we're done */
if ((header.bDescriptorType == USB_DT_ENDPOINT) ||
(header.bDescriptorType == USB_DT_INTERFACE) ||
(header.bDescriptorType == USB_DT_CONFIG) ||
(header.bDescriptorType == USB_DT_DEVICE))
break;
if (usb_debug >= 2)
fprintf(stderr, "skipping descriptor 0x%X\n", header.bDescriptorType);
numskipped++;
buffer += header.bLength;
size -= header.bLength;
}
if (numskipped && usb_debug >= 2)
fprintf(stderr, "skipped %d class/vendor specific endpoint descriptors\n", numskipped);
/* Copy any unknown descriptors into a storage area for */
/* drivers to later parse */
len = (int)(buffer - begin);
if (len) {
/* FIXME: We should realloc and append here */
if (!config->extralen) {
config->extra = malloc(len);
if (!config->extra) {
if (usb_debug >= 1)
fprintf(stderr, "couldn't allocate memory for config extra descriptors\n");
config->extralen = 0;
return -1;
}
memcpy(config->extra, begin, len);
config->extralen = len;
}
}
retval = usb_parse_interface(config->interface + i, buffer, size);
if (retval < 0)
return retval;
buffer += retval;
size -= retval;
}
return size;
}
void usb_destroy_configuration(struct usb_device *dev)
{
int c, i, j, k;
if (!dev->config)
return;
for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
struct usb_config_descriptor *cf = &dev->config[c];
if (!cf->interface)
continue;
for (i = 0; i < cf->bNumInterfaces; i++) {
struct usb_interface *ifp = &cf->interface[i];
if (!ifp->altsetting)
continue;
for (j = 0; j < ifp->num_altsetting; j++) {
struct usb_interface_descriptor *as = &ifp->altsetting[j];
if (as->extra)
free(as->extra);
if (!as->endpoint)
continue;
for (k = 0; k < as->bNumEndpoints; k++) {
if (as->endpoint[k].extra)
free(as->endpoint[k].extra);
}
free(as->endpoint);
}
free(ifp->altsetting);
}
free(cf->interface);
}
free(dev->config);
}
void usb_fetch_and_parse_descriptors(usb_dev_handle *udev)
{
struct usb_device *dev = udev->device;
int i;
if (dev->descriptor.bNumConfigurations > USB_MAXCONFIG) {
if (usb_debug >= 1)
fprintf(stderr, "Too many configurations (%d > %d)\n", dev->descriptor.bNumConfigurations, USB_MAXCONFIG);
return;
}
if (dev->descriptor.bNumConfigurations < 1) {
if (usb_debug >= 1)
fprintf(stderr, "Not enough configurations (%d < %d)\n", dev->descriptor.bNumConfigurations, 1);
return;
}
dev->config = (struct usb_config_descriptor *)malloc(dev->descriptor.bNumConfigurations * sizeof(struct usb_config_descriptor));
if (!dev->config) {
if (usb_debug >= 1)
fprintf(stderr, "Unable to allocate memory for config descriptor\n");
return;
}
memset(dev->config, 0, dev->descriptor.bNumConfigurations *
sizeof(struct usb_config_descriptor));
for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
unsigned char buffer[8], *bigbuffer;
struct usb_config_descriptor config;
int res;
/* Get the first 8 bytes so we can figure out what the total length is */
res = usb_get_descriptor(udev, USB_DT_CONFIG, (unsigned char)i, buffer, 8);
if (res < 8) {
if (usb_debug >= 1) {
if (res < 0)
fprintf(stderr, "Unable to get descriptor (%d)\n", res);
else
fprintf(stderr, "Config descriptor too short (expected %d, got %d)\n", 8, res);
}
goto err;
}
usb_parse_descriptor(buffer, "bbw", &config);
bigbuffer = malloc(config.wTotalLength);
if (!bigbuffer) {
if (usb_debug >= 1)
fprintf(stderr, "Unable to allocate memory for descriptors\n");
goto err;
}
res = usb_get_descriptor(udev, USB_DT_CONFIG, (unsigned char)i, bigbuffer,
config.wTotalLength);
if (res < config.wTotalLength) {
if (usb_debug >= 1) {
if (res < 0)
fprintf(stderr, "Unable to get descriptor (%d)\n", res);
else
fprintf(stderr, "Config descriptor too short (expected %d, got %d)\n", config.wTotalLength, res);
}
free(bigbuffer);
goto err;
}
res = usb_parse_configuration(&dev->config[i], bigbuffer);
if (usb_debug >= 2) {
if (res > 0)
fprintf(stderr, "Descriptor data still left\n");
else if (res < 0)
fprintf(stderr, "Unable to parse descriptors\n");
}
free(bigbuffer);
}
return;
err:
free(dev->config);
dev->config = NULL;
}
|
tinyos-io/tinyos-3.x-contrib | tcd/powertossim-z/tinyos_files/tinyos-2.0.2/tos/chips/atm128/Atm128I2C.h | <gh_stars>0
// $Id: Atm128I2C.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_Atm128I2C_h
#define _H_Atm128I2C_h
//====================== I2C Bus ==================================
/* SCL freq = CPU freq / (16 + 2(TWBR) * pow(4, TWPR)) */
enum {
ATM128_I2C_RATE_DIVIDE_16 = 0,
ATM128_I2C_RATE_DIVIDE_24 = 1,
ATM128_I2C_RATE_DIVIDE_80 = 2,
}
typedef uint8_t Atm128_TWBR_t; //!< Two Wire Bit Rate Register
/* I2C Control Register */
typedef struct
{
uint8_t twie : 1; //!< Two Wire Interrupt Enable
uint8_t rsvd : 1; //!< Reserved
uint8_t twen : 1; //!< Two Wire Enable Bit
uint8_t twwc : 1; //!< Two Wire Write Collision Flag
uint8_t twsto : 1; //!< Two Wire Stop Condition Bit
uint8_t twsta : 1; //!< Two Wire Start Condition Bit
uint8_t twea : 1; //!< Two Wire Enable Acknowledge Bit
uint8_t twint : 1; //!< Two Wire Interrupt Flag
} Atm128I2CControl_t;
typedef Atm128I2CControl_t Atm128_TWCR_t; //!< Two Wire Control Register
/* SCL freq = CPU freq / (16 + 2(TWBR) * pow(4, TWPR)) */
enum {
ATM128_I2C_PRESCALE_1 = 0,
ATM128_I2C_PRESCALE_4 = 1,
ATM128_I2C_PRESCALE_16 = 2,
ATM128_I2C_PRESCALE_64 = 3,
};
enum {
ATM128_I2C_STATUS_START = 1,
};
/* I2C Status Register */
typedef struct
{
uint8_t twps : 2; //!< Two Wire Prescaler Bits
uint8_t rsvd : 1; //!< Reserved
uint8_t tws : 5; //!< Two Wire Status
} Atm128I2CStatus_t;
typedef Atm128I2CStatus_t Atm128_TWCR_t; //!< Two Wire Status Register
typedef uint8_t Atm128_TWDR_t; //!< Two Wire Data Register
typedef uint8_t Atm128_TWAR_t; //!< Two Wire Slave Address Register
#endif //_H_Atm128I2C_h
|
tinyos-io/tinyos-3.x-contrib | wsu/tools/simx/simx/python/simx/act/React.h | <reponame>tinyos-io/tinyos-3.x-contrib<filename>wsu/tools/simx/simx/python/simx/act/React.h
/*
Messages understood by TReact.
Since these messages are ONLY transfered between the Python TReact
driver and an external application the message size is restricted
only by the size that the serial-forward protocol can handle. As
such, assuming a fixed 10 bytes for AM overhead, 245 bytes are
available for payload.
*/
#include "AM.h"
enum {
AM_REACT = 239,
AM_REACT_BASE = AM_REACT,
/* These are AM_* to make MIG happy and have a standard accessor in
the generated classes. However, since (if) they are encoded into
React messages, they will never be used as real AM-types. */
AM_REACT_CMD_BASE = 200,
AM_REACT_WATCH,
AM_REACT_BIND_WATCH_BASE,
AM_REACT_NODE_INFO,
AM_REACT_REPLY,
AM_REACT_LINK,
AM_REACT_PROBE,
AM_TIME_EVENT
};
/*
Other react messages are packed int react_base. This has some
advantages 1) using only one AM id which reduces potential conflicts
2) being able to easily split other messages up over several packets
3) having a unified tracking system.
*/
enum {
MAX_REACT_PAYLOAD = 240,
};
nx_struct react_base {
/* Tracking ID. This can be specified during encoding and retrieved
during decoding. The use is application-specific. */
nx_uint16_t track_id;
/* AM-type of encoded messages. 0 signifies that this message
contains more data belonging to an earlier message. */
nx_am_id_t type;
/* Total length of remaining data. This may exceed MAX_REACT_PAYLOAD
which means that data is encoded into futures react messages as
well. */
nx_uint16_t remaining;
nx_uint8_t payload_start_byte;
};
typedef nx_uint16_t nx_var_id_t;
/*
Used to transfer commands from React to Act environment.
*/
nx_struct react_cmd_base {
nx_uint8_t type;
nx_int8_t ve_start_byte;
};
/*
Text-based replies.
*/
enum {
/* outcome of command/request */
RESULT_SUCCESS = 0, /* request completely accepted */
RESULT_FAILURE, /* request rejected */
RESULT_PARTIAL, /* request partially accepted */
RESULT_UNSOLICITED, /* reply not in response to particular request */
/* refinements */
REFINE_NORMAL = 1,
REFINE_INFO,
REFINE_WARN,
REFINE_ERROR,
REFINE_FATAL,
REFINE_DEBUG
};
nx_struct react_reply {
nx_uint8_t status;
/* \0 separated entries. The first byte of each entry represents the
refinemnet type. Thus, it is possible to send multiple RELATED
replies at the same time. The contents of each entry itself is
not defined. */
nx_int8_t ve_start_byte;
};
/*
Reply: new or existing watched variable binding.
*/
nx_struct react_bind_watch_base {
nx_am_addr_t node;
nx_var_id_t var_id;
nx_uint8_t var_type;
/* encoded varname \0 watchexpr */
nx_int8_t ve_start_byte;
};
/*
Reply: watched value.
*/
nx_struct react_watch {
/*
ID associated with value; this is established when the monitor is
first setup.
*/
nx_var_id_t var_id;
nx_int8_t ve_start_byte;
};
/*
Message sent when a change in data is detected. The payload is the
literal data of the data. It is up the reciever to correctly decode
it.
*/
nx_struct react_probe {
nx_var_id_t binding;
nx_am_addr_t mote;
nx_int8_t ve_start_byte;
};
/*
Information pertaining to topology. This is a crummy named.
*/
enum { // for status below
/* is node on? */
NODE_ON = 0x01, // bit-mask, 1st bit
/* node not configured or in an invalid configuration */
NODE_INVALID = 0x02, // bit-mask, 2nd bit
/* node position or power changed but topology is not updated */
NODE_STALE = 0x04 // bit-mask, 3rd bit
};
nx_struct react_node_info {
nx_am_addr_t id;
nx_uint8_t status; // see enum above
nx_int32_t x; // position, x,y in in cm
nx_int32_t y;
nx_int8_t txpower; // gain @ 0
nx_int8_t pld0; // gain @ pld0
};
enum {
INVALID_LINK = 127, // Link is invalid and should be removed
IGNORE_LINK = 126 // Ignore this link-gain value (e.g. set only one way)
};
nx_struct react_link {
nx_am_addr_t node1;
nx_am_addr_t node2;
// Link-gain in dBm or INVALID_LINK/IGNORE_LINK
nx_int8_t gain1to2;
nx_int8_t gain2to1;
};
enum {
EVT_RUNNING = 0,
EVT_STOPPED,
EVT_RESUMED
};
nx_struct time_event {
nx_uint16_t event_type;
/* sim-time (64-bits) */
nx_uint32_t timeH;
nx_uint32_t timeL;
};
|
tinyos-io/tinyos-3.x-contrib | tinymulle/tos/platforms/mulle/chips/rv8564/rv8564.h | <gh_stars>1-10
/*
* Copyright (c) 2008 EISLAB, Lulea University of Technology
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is for the Microcrystal RV-8564 Real-time Clock on the Mulle platform.
*
* Author: <NAME> <>
*
*/
#ifndef __RV8564_H__
#define __RV8564_H__
/* constants */
#define RV8564_WR_ADDR 0xa2 //slave address write 0xa2 or read 0xa3
#define RV8564_RD_ADDR 0xa3
#define RV8564_CS1 0x00
#define RV8564_CS2 0x01
/* Control/Status registers */
#define RV8564_CTR1 0x00 //00 Control status 1,
//Test1 0 Stop 0, Test 0 0 0
#define RV8564_CTR2 0x01 //01 Control status 2,
// 0 x 0 TI/TP, AF TF AIE TIE
// TI/TP=1,INT pulses
//Note that writing 1 to the alarm flags causes no change...0-1 is not applied.
#define RV8564_SEC 0x02 //
#define RV8564_MIN 0x03 //
#define RV8564_HOUR 0x04 //
#define RV8564_DAY 0x05 //
#define RV8564_WEEK 0x06 //
#define RV8564_MON 0x07 //
#define RV8564_YEAR 0x08 //
#define RV8564_MIN_ALARM 0x09 //
#define RV8564_HR_ALARM 0x0A //
#define RV8564_DAY_ALARM 0x0B //
#define RV8564_WK_ALARM 0x0C //
#define RV8564_CLKF 0x0D //FE x x x, x x FD1 FD0
// 0 0 32768 Hz
// 0 1 61024 Hz
// 1 0 32 Hz
// 1 1 1 Hz
#define RV8564_TC 0x0E //TE x x x, x x TD1 TD0
// 0 0 4096 Hz
// 0 1 64 Hz
// 1 0 1 Sec
// 1 1 1 Min
#define RV8564_TIMER 0x0F //128 64 32 16, 8 4 2 1
/*********** Initial setting of the RV_8564ram, Set it before using (debug only) ***********/
uint8_t RV_8564ram[16] = { 0x00, 0x13, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01,
0x07, 0x80, 0x80, 0x80,
0x80, 0x83, 0x83, 1 };
#endif /* __RV8564_H__ */
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/linuxsim/simworld.h | #ifndef SIM_WORLD_H
#define SIM_WORLD_H
#include <pthread.h>
#define ACTION_USER 10
#define ENERGY_TIME 5 //seconds in between energy updates
typedef void (*__energyfunc) (int, int, unsigned int);
extern unsigned int predict_src_energy(unsigned int hours);
extern unsigned int get_battery_size();
extern unsigned int get_current_time();
extern int set_energy_callback(__energyfunc func);
extern int get_sensor_reading();
extern int recv_network_int();
extern void send_network_int(int value);
//THREAD FUNCTIONS
int sim_pthread_create (pthread_t *__restrict __threadp,
__const pthread_attr_t *__restrict __attr,
void *(*__start_routine) (void *),
void *__restrict __arg);
void __attribute__((noreturn)) sim_pthread_exit(void *value_ptr);
unsigned int sim_sleep (unsigned int __seconds);
int sim_usleep (__useconds_t __useconds);
#endif
|
tinyos-io/tinyos-3.x-contrib | ecosensory/apps/ReadMoistureSensors/ReadMoistureSensors.h | /* Copyright (c) 2007, Ecosensory Austin Texas All rights reserved.
* This code funded by TX State San Marcos University. BSD license full text at:
* http://tinyos.cvs.sourceforge.net/tinyos/tinyos-2.x-contrib/ecosensory/license.txt
* by <NAME> <<EMAIL>>
* Rev 1.0 14 Dec 2007
*/
#ifndef READMOISTURESENSORS_H
#define READMOISTURESENSORS_H
enum {
ALWAYS_SHUTOFF_MILLI = 180, // a2d reading delta t after sensors powered.
ECH2O_WARMUP_MILLI = 80, // a2d reading delta t after sensors powered.
TIMER_PERIOD_MILLI = 1000, // a2d reading period.
// AM_MOISTURESENSORSMSG is an active message type. Depends on Makefile
// BUILD_EXTRA_DEPS=MoistureSensorsMsg.class
// MoistureSensorsMsg.class: MoistureSensorsMsg.java
// and MoistureSensorsMsg.java:
// see tos/types/AM.h for other basic definitions related.
AM_MOISTURESENSORSMSG = 6,
TOS_NODEID = 22
};
typedef nx_struct MoistureSensorsMsg {
nx_uint16_t nodeid;
nx_uint16_t adc00; // bank 0, channel 0
nx_uint16_t adc01; // bank 0, channel 1
nx_uint16_t adc02; // bank 0, channel 2
nx_uint16_t adc03; // bank 0, channel 3
nx_uint16_t adc04; // bank 0, channel 4
nx_uint16_t adc05; // bank 0, channel 5
nx_uint16_t adc10; // bank 1, channel 0
nx_uint16_t adc11; // bank 1, channel 1
nx_uint16_t adc12; // bank 1, channel 2
nx_uint16_t adc13; // bank 1, channel 3
nx_uint16_t adc14; // bank 1, channel 4
nx_uint16_t adc15; // bank 1, channel 5
nx_uint16_t timestamp;
} MoistureSensorsMsg;
#endif
|
tinyos-io/tinyos-3.x-contrib | tcd/powertossim-z/powercurses/strarg.c | <reponame>tinyos-io/tinyos-3.x-contrib
#include <stdlib.h>
#include <string.h>
/*
strarg("a b c d e f", " ", 1); => a
strarg(" a b ", " ", 2); => b
strarg(",.a,.b,.c,.", ".,", 3); => c
strarg(" ,. ; a... cdef", " ;,.c", 2) => def (1 would be "a")
*/
char *strarg( const char *str, const char *delims, size_t arg )
{
char *p = 0;
int len;
if (arg < 1 || !str || !delims)
return 0;
while (strchr(delims, *str) && *str++);
while ( (len = strcspn(str, delims)) && --arg ) {
str += len;
while (strchr(delims, *str) && *str++);
}
if (!len)
return NULL;
p = malloc(len + 1);
strncpy(p, str, len)[len] = '\0';
return p;
}
|
tinyos-io/tinyos-3.x-contrib | intelmote2/support/sdk/c/compress/codeZeros.h | <filename>intelmote2/support/sdk/c/compress/codeZeros.h
/*
* Copyright (c) 2006 Stanford University.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
* - Neither the name of the Stanford University nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STANFORD
* UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @author <NAME> (<EMAIL>)
*/
//- run-length code all zeros assuming that all data are encoded using 7 bits,
// thus data|0x80 encodes data, num&0x7F encodes number of consecutive zeros,
// and 0 is a special symbol meaning that the rest of the data is all zeros
//- dataIn contains input data
//- dataOut is a placeholder for the run-length code
//- dataSize is the size of the input data
//- bandwidth specifies limit on the size of the encoded sequence, all entries
// beyond bandwidth will be set to zero
//- command returns the length of the encoded sequence
static inline uint32_t codeZeros(uint8_t *dataIn, uint8_t *dataOut, uint32_t dataSize,
uint32_t bandwidth)
{
uint32_t i;
uint32_t idx=0;
uint16_t zeroSeqLength=0, numZeroFreqs=0;
for (i=0; (i<dataSize && idx<(bandwidth-3)); i++)
{
int8_t value = dataIn[i];
if (value==0)
{
if (zeroSeqLength++==0x7F)
{
++numZeroFreqs;
zeroSeqLength=1;
}
}
else
{
if (zeroSeqLength>0)
{
while (numZeroFreqs>0)
{
numZeroFreqs--;
dataOut[idx++] = 0x7F;
}
dataOut[idx++] = zeroSeqLength&0x7F;
zeroSeqLength = 0;
}
//hardcoded 7bits per value
if (value<=-64)
{value=-64;}
else if (value>=63)
{value = 63;}
dataOut[idx++] = value|0x80;
}
}
// zero(0) is a special symbol meaning that there are zeros until the end of file
// if ( zeroSeqLength>0 ||
// (idx<dataSize && idx>=bandwidth))
dataOut[idx++]=0;
return idx;//*/
}
static inline uint32_t codeDC(uint8_t *dataIn, uint8_t *dataOut, uint16_t dataSize)
{
uint16_t i;
dataOut[0]=dataIn[0];
for (i=1; i<dataSize; i++)
dataOut[i]=dataIn[i-1]-dataIn[i];
return dataSize;
}
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/simulator/energypredictor.h | /* This is the same predictor used in the HelioMote project
* It is a simple autoregressive filter of order 1.
*
*
*/
#ifndef ENERGYPREDICTOR_H
#define ENERGYPREDICTOR_H
#include "simulator.h"
#include "nodes.h"
using namespace std;
#ifndef EP_EPOCH_HRS
#define EP_EPOCH_HRS 24
#endif
#ifndef EP_FILTER_WT
#define EP_FILTER_WT 90
#endif
int64_t start_energy;
int64_t min_time;
int64_t ep_last_prediction;
int64_t ep_cur_prediction;
int64_t ep_last_error;
int64_t ep_start_epoch;
int64_t ep_energy_counter;
void init_energy_predictor()
{
ep_start_epoch = 0;
ep_energy_counter = 0;
ep_cur_prediction = 0;
}
void ep_more_energy(int64_t energy, int64_t timestamp)
{
int64_t diff = timestamp - ep_start_epoch;
if (diff > (EP_EPOCH_HRS * 60 * 60 * 1000))
{
int64_t last_prediction = ep_cur_prediction;
int64_t delta;
ep_cur_prediction = ((ep_energy_counter * EP_FILTER_WT) + (last_prediction * (100-EP_FILTER_WT)))/100;
ep_last_error = ::llabs((int64_t)(ep_cur_prediction - last_prediction));
ep_energy_counter = 0;
ep_start_epoch = ep_start_epoch + (EP_EPOCH_HRS * 60 * 60 * 1000);
printf("ep(%lld,%lld)\n",ep_cur_prediction, last_prediction);
}
ep_energy_counter += energy;
}
int64_t predict_energy(vector<event_t*>* timeline,
int64_t current_index,
int64_t hours)
{
int64_t result;
double confidence;
if (ep_last_error < ep_cur_prediction)
{
confidence =1.0 - ((double)ep_last_error / (double)ep_cur_prediction);
} else {
confidence = 0;
}
//result = (int64_t)(confidence * (double)((ep_cur_prediction / 24) * hours));
result = ((ep_cur_prediction / 24) * hours);
return result;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | tinybotics/tos/chips/xbee/Xbee.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
*
* 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.
*/
/*
* XBee packet format (CC2420-like)
*
* @author <NAME> <<EMAIL>>
* @author <NAME>
* @author <NAME> <<EMAIL>>
*/
#ifndef __XBEE_H__
#define __XBEE_H__
#include "AM.h"
/* header - we take into account possible usage of 64-bit addressing modes in the future*/
enum xbee_api_enums {
XBEE_API_MODEM_STATUS = 0x8A,
XBEE_API_AT_COMMAND = 0x08,
XBEE_API_AT_COMMAND_QUEUE = 0x09,
XBEE_API_AT_COMMAND_RESPONSE = 0x88,
XBEE_API_TX_64BIT = 0x00,
XBEE_API_TX_16BIT = 0x01,
XBEE_API_TX_STATUS = 0x89,
XBEE_API_RX_64BIT = 0x80,
XBEE_API_RX_16BIT = 0x81,
};
enum xbee_ascii_enums {
ASCII_A = 0x41,
ASCII_C = 0x43,
ASCII_D = 0x44,
ASCII_H = 0x48,
ASCII_I = 0x49,
ASCII_L = 0x4C,
ASCII_M = 0x4D,
ASCII_P = 0x50,
ASCII_Y = 0x59,
ASCII_T = 0x54,
};
#define XBEE_16BIT_ADDRESSING
#ifdef XBEE_16BIT_ADDRESSING
#define ADDRESS_LENGTH 2
#define XBEE_API_TX XBEE_API_TX_16BIT
#endif
#ifdef XBEE_64BIT_ADDRESSING
#define ADDRESS_LENGTH 8
#define XBEE_API_TX XBEE_API_TX_64BIT
#endif
// the active message (AM) format
typedef nx_struct xbee_header {
nx_uint8_t api;
#ifdef XBEE_16BIT_ADDRESSING
nx_uint8_t opt[4];
#endif
#ifdef XBEE_64BIT_ADDRESSING
nx_uint8_t opt[10];
#endif
/** I-Frame 6LowPAN interoperability byte */
#ifdef XBEE_IFRAME_TYPE
nx_uint8_t network;
#endif
nx_am_id_t type;
} xbee_header_t;
typedef nx_struct xbee_footer {
} xbee_footer_t;
typedef nx_struct xbee_metadata {
nx_uint8_t length;
//nx_uint8_t dsn; // sequence numer = frame id
nx_bool ack; // TRUE=packet was acked
nx_bool ack_req; // TRUE=ack requested for this packet
nx_uint8_t rssi;
/** Packet Link Metadata */
#ifdef PACKET_LINK
nx_uint16_t maxRetries;
nx_uint16_t retryDelay;
#endif
} xbee_metadata_t;
typedef nx_struct xbee_packet_t {
xbee_header_t header;
nx_uint8_t data[];
} xbee_packet_t;
// the service and status message (SM) format
// (status reports, module configuration, op status, etc)
typedef nx_struct xbee_service_header {
nx_uint8_t api;
} xbee_service_header_t;
typedef nx_struct xbee_service_packet_t {
xbee_service_header_t header;
nx_uint8_t data[];
} xbee_service_packet_t;
// the payload structure of a status message
/*
typedef nx_struct statusMsg {
nx_uint8_t frameID;
nx_uint8_t status;
} statusMsg;
*/
#ifndef TOSH_DATA_LENGTH
#define TOSH_DATA_LENGTH 28
#endif
#ifndef XBEE_DEF_CHANNEL
#define XBEE_DEF_CHANNEL 26
#endif
#ifndef XBEE_DEF_RFPOWER
#define XBEE_DEF_RFPOWER 4 // 0 dBm, as CC2420's default
#endif
/**
* Ideally, your receive history size should be equal to the number of
* RF neighbors your node will have
*/
#ifndef RECEIVE_HISTORY_SIZE
#define RECEIVE_HISTORY_SIZE 4
#endif
/**
* The 6LowPAN ID has yet to be defined for a TinyOS network.
*/
#ifndef TINYOS_6LOWPAN_NETWORK_ID
#define TINYOS_6LOWPAN_NETWORK_ID 0x0
#endif
// message_t type dispatch
enum {
XBEE_ACTIVE_MESSAGE_ID = 0,
XBEE_TX_STATUS_MESSAGE_ID = 1,
XBEE_AT_STATUS_MESSAGE_ID = 2,
XBEE_SERVICE_MESSAGE_ID = 3,
XBEE_UNKNOWN_ID = 255,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/linuxsim/rt_handler.c |
#include "rt_handler.h"
#include "../mNodes.h"
//extern int curstate;
//extern float curgrade;
//extern int32_t timerVals[NUMSOURCES][NUMSTATES][2];
unsigned int get_timer_interval(int source)
{
unsigned int minval, maxval;
minval = timerVals[source][curstate][0];
maxval = timerVals[source][curstate][1];
double tdelta = (double)(maxval-minval);
double dval = ((double)maxval) - (curgrade * tdelta);
//convert to 1/100 seconds
uint32_t newval = (uint32_t)rint(dval / 10.0);
return newval;
}
int isFunctionalState(int8_t state)
{
return (curstate >= state);
}
void reportError(uint16_t nodeid, uint8_t error, rt_data _pdata)
{
//printf("ERROR: %i:%i\n",nodeid, _pdata.weight);
reportExit(_pdata);
}
void reportExit(rt_data _pdata)
{
int result;
//printf("Flow done: %i\n",_pdata.weight);
end_path(_pdata.sessionID, _pdata.weight);
}
int getNextSession()
{
static int session= 0;
session++;
return session;
}
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/stargate/sfaccess/Semaphore.h | /****************************************************************************\
*
* 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.
*
\****************************************************************************/
#ifndef SEMAPHORES
#define SEMAPHORES
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#ifndef pthread_mutexattr_default
#define pthread_mutexattr_default NULL
#endif
#ifndef pthread_condattr_default
#define pthread_condattr_default NULL
#endif
typedef struct Semaphore
{
int v;
pthread_mutex_t mutex;
pthread_cond_t cond;
} Semaphore;
int semaphore_down (Semaphore * s);
int semaphore_decrement (Semaphore * s);
int semaphore_up (Semaphore * s);
void semaphore_destroy (Semaphore * s);
void semaphore_init (Semaphore * s);
int semaphore_value (Semaphore * s);
int tw_pthread_cond_signal (pthread_cond_t * c);
int tw_pthread_cond_wait (pthread_cond_t * c, pthread_mutex_t * m);
int tw_pthread_mutex_unlock (pthread_mutex_t * m);
int tw_pthread_mutex_lock (pthread_mutex_t * m);
void do_error (char *msg);
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/tinyos2/SolarSrc.h | <filename>eon/eon/src/runtime/tinyos2/SolarSrc.h<gh_stars>1-10
#ifndef SOLARSRC_H_INCLUDED
#define SOLARSRC_H_INCLUDED
#define _NUMEPOCHS 12L
#define _HRS_PER_DAY 24L
#define _DAYLENGTH (_HRS_PER_DAY * 60L)
#define _EPOCHLENGTH (_DAYLENGTH / _NUMEPOCHS)
#define _HRS_PER_EP (_HRS_PER_DAY / _NUMEPOCHS)
#endif
|
tinyos-io/tinyos-3.x-contrib | csau/misc/apps/tests/Ieee154Test/src/Ieee154Test.h | #ifndef IEEE154TEST_H
#define IEEE154TEST_H
#include "message.h"
enum {
AM_TEST_MSG = 10,
#ifdef TOSSIM
SENDER_ID = 0,
RECEIVER_ID = 1,
#else
SENDER_ID = 2,
RECEIVER_ID = 3,
#endif
};
typedef nx_struct test_msg {
nx_uint8_t data[TOSH_DATA_LENGTH];
} test_msg_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | uob/tossdr/tos/lib/tossdr/packet.c | <filename>uob/tossdr/tos/lib/tossdr/packet.c
/*
* "Copyright (c) 2005 Stanford University. All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose, without fee, and without written
* agreement is hereby granted, provided that the above copyright
* notice, the following two paragraphs and the author appear in all
* copies of this software.
*
* IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF STANFORD UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND STANFORD UNIVERSITY
* HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
* ENHANCEMENTS, OR MODIFICATIONS."
*/
/**
*
* Injecting packets into TOSSIM.
*
* @author <NAME>
* @date Dec 10 2005
*/
#include <packet.h>
#include <sim_packet.h>
Packet::Packet() {
msgPtr = sim_packet_allocate();
allocated = 1;
}
Packet::Packet(sim_packet_t* m) {
if (m != NULL) {
msgPtr = m;
allocated = 0;
}
else {
msgPtr = sim_packet_allocate();
allocated = 1;
}
}
Packet::~Packet() {
if (allocated) {
sim_packet_free(msgPtr);
}
}
void Packet::setSource(int src) {
sim_packet_set_source(msgPtr, (uint16_t)src);
}
int Packet::source() {
return sim_packet_source(msgPtr);
}
void Packet::setDestination(int dest) {
sim_packet_set_destination(msgPtr, (uint16_t)dest);
}
int Packet::destination() {
return sim_packet_destination(msgPtr);
}
void Packet::setLength(int len) {
sim_packet_set_length(msgPtr, (uint8_t)len);
}
int Packet::length() {
return sim_packet_length(msgPtr);
}
void Packet::setType(int type) {
sim_packet_set_type(msgPtr, (uint8_t)type);
}
int Packet::type() {
return sim_packet_type(msgPtr);
}
char* Packet::data() {
char* val = (char*)sim_packet_data(msgPtr);
return val;
}
void Packet::setData(char* data, int len) {
len = (len > maxLength())? maxLength():len;
memcpy(sim_packet_data(msgPtr), data, len);
setLength(len);
}
int Packet::maxLength() {
return (int)sim_packet_max_length(msgPtr);
}
void Packet::setStrength(int str) {
sim_packet_set_strength(msgPtr, (uint16_t)str);
}
sim_packet_t* Packet::getPacket() {
return msgPtr;
}
void Packet::deliver(int node, long long int t) {
sim_packet_deliver(node, msgPtr, t);
}
void Packet::deliverNow(int node) {
deliver(node, 0);
}
|
tinyos-io/tinyos-3.x-contrib | ethz/nodule/support/make/avr32/startup/include/exception.h | <gh_stars>0
/* $Id: exception.h,v 1.1 2008/01/07 14:20:00 yuecelm Exp $ */
/* author: <NAME> <<EMAIL>> */
#ifndef __AVR32_EXCEPTION__
#define __AVR32_EXCEPTION__
/**
* Exception vector offsets
*/
#define EVBA_UNRECOVERABLE 0x000
#define EVBA_TLB_MULTIPLE 0x004
#define EVBA_BUS_ERROR_DATA 0x008
#define EVBA_BUS_ERROR_INSTR 0x00C
#define EVBA_NMI 0x010
#define EVBA_INSTR_ADDR 0x014
#define EVBA_ITLB_MISS 0x050
#define EVBA_ITLB_PROT 0x018
#define EVBA_BREAKPOINT 0x01C
#define EVBA_ILLEGAL_OPCODE 0x020
#define EVBA_UNIMPLEMENTED 0x024
#define EVBA_PRIVILEGE_VIOL 0x028
#define EVBA_FLOATING_POINT 0x02C
#define EVBA_COP_ABSENT 0x030
#define EVBA_SCALL 0x100
#define EVBA_DATA_ADDR_R 0x034
#define EVBA_DATA_ADDR_W 0x038
#define EVBA_DTLB_MISS_R 0x060
#define EVBA_DTLB_MISS_W 0x070
#define EVBA_DTLB_PROT_R 0x03C
#define EVBA_DTLB_PROT_W 0x040
#define EVBA_DTLB_MODIFIED 0x044
/**
* The exception handler should return the address which the exception calls after the exception processing.
*/
unsigned int __attribute__((C, spontaneous)) exception_handler(int evba_offset, int return address);
/**
* The supervision call handler.
*/
void __attribute__((C, spontaneous)) scall_handler(int code, int p1, int p2, int p3, int p4);
#endif
|
tinyos-io/tinyos-3.x-contrib | intelmote2/support/sdk/c/compress/huffmanCompress.h | <filename>intelmote2/support/sdk/c/compress/huffmanCompress.h<gh_stars>1-10
/*************************************************************************
* Name: huffman.c
* Author: <NAME>
* Description: Huffman coder/decoder implementation.
* Reentrant: Yes
*
* This is a very straight forward implementation of a Huffman coder and
* decoder.
*
* Primary flaws with this primitive implementation are:
* - Slow bit stream implementation
* - Maximum tree depth of 32 (the coder aborts if any code exceeds a
* size of 32 bits). If I'm not mistaking, this should not be possible
* unless the input buffer is larger than 2^32 bytes, which is not
* supported by the coder anyway (max 2^32-1 bytes can be specified with
* an unsigned 32-bit integer).
*
* On the other hand, there are a few advantages of this implementation:
* - The Huffman tree is stored in a very compact form, requiring only
* 10 bits per symbol (for 8 bit symbols), meaning a maximum of 320
* bytes overhead.
* - The code should be fairly easy to follow, if you are familiar with
* how the Huffman compression algorithm works.
*
* Possible improvements (probably not worth it):
* - Partition the input data stream into blocks, where each block has
* its own Huffman tree. With variable block sizes, it should be
* possible to find locally optimal Huffman trees, which in turn could
* reduce the total size.
* - Allow for a few different predefined Huffman trees, which could
* reduce the size of a block even further.
*-------------------------------------------------------------------------
* Copyright (c) 2003-2006 <NAME>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
* <NAME>
* marcus.geelnard at home.se
*************************************************************************/
/*************************************************************************
* Types used for Huffman coding
*************************************************************************/
typedef struct {
uint8_t *BytePtr;
uint16_t BitPos;
} huff_bitstream_t;
typedef struct {
int16_t Symbol;
uint16_t Count;
uint16_t Code;
uint16_t Bits;
} huff_sym_t;
typedef struct huff_encodenode_struct huff_encodenode_t;
struct huff_encodenode_struct {
huff_encodenode_t *ChildA, *ChildB;
int16_t Count;
int16_t Symbol;
};
typedef struct huff_decodenode_struct huff_decodenode_t;
struct huff_decodenode_struct {
huff_decodenode_t *ChildA, *ChildB;
int16_t Symbol;
};
/*************************************************************************
* Constants for Huffman decoding
*************************************************************************/
/* The maximum number of nodes in the Huffman tree is 2^(8+1)-1 = 511 */
#define MAX_TREE_NODES 511
/*************************************************************************
* _Huffman_InitBitstream() - Initialize a bitstream.
*************************************************************************/
static void _Huffman_InitBitstream( huff_bitstream_t *stream, uint8_t *buf )
{
stream->BytePtr = buf;
stream->BitPos = 0;
}
/*************************************************************************
* _Huffman_WriteBits() - Write bits to a bitstream.
*************************************************************************/
static void _Huffman_WriteBits( huff_bitstream_t *stream, uint16_t x, uint16_t bits )
{
uint16_t bit, count;
uint8_t *buf;
uint16_t mask;
/* Get current stream state */
buf = stream->BytePtr;
bit = stream->BitPos;
/* Append bits */
mask = 1 << (bits-1);
for( count = 0; count < bits; ++ count )
{
*buf = (*buf & (0xff^(1<<(7-bit)))) +
((x & mask ? 1 : 0) << (7-bit));
x <<= 1;
bit = (bit+1) & 7;
if( !bit )
++ buf;
}
/* Store new stream state */
stream->BytePtr = buf;
stream->BitPos = bit;
}
/*************************************************************************
* _Huffman_Hist() - Calculate (sorted) histogram for a block of data.
*************************************************************************/
static void _Huffman_Hist( uint8_t *in, huff_sym_t *sym, uint16_t size )
{
int16_t k;
/* Clear/init histogram */
for( k = 0; k < 256; ++ k )
{
sym[k].Symbol = k;
sym[k].Count = 0;
sym[k].Code = 0;
sym[k].Bits = 0;
}
/* Build histogram */
for( k = size; k; -- k )
sym[*in ++].Count ++;
}
/*************************************************************************
* _Huffman_StoreTree() - Store a Huffman tree in the output stream and
* in a look-up-table (a symbol array).
*************************************************************************/
static void _Huffman_StoreTree( huff_encodenode_t *node, huff_sym_t *sym,
huff_bitstream_t *stream, uint16_t code, uint16_t bits )
{
uint16_t sym_idx;
/* Is this a leaf node? */
if( node->Symbol >= 0 )
{
/* Append symbol to tree description */
_Huffman_WriteBits( stream, 1, 1 );
_Huffman_WriteBits( stream, node->Symbol, 8 );
/* Find symbol index */
for( sym_idx = 0; sym_idx < 256; ++ sym_idx )
if( sym[sym_idx].Symbol == node->Symbol ) break;
/* Store code info in symbol array */
sym[sym_idx].Code = code;
sym[sym_idx].Bits = bits;
return;
}
else
/* This was not a leaf node */
_Huffman_WriteBits( stream, 0, 1 );
/* Branch A */
_Huffman_StoreTree( node->ChildA, sym, stream, (code<<1)+0, bits+1 );
/* Branch B */
_Huffman_StoreTree( node->ChildB, sym, stream, (code<<1)+1, bits+1 );
}
/*************************************************************************
* _Huffman_MakeTree() - Generate a Huffman tree.
*************************************************************************/
static void _Huffman_MakeTree( huff_sym_t *sym, huff_bitstream_t *stream )
{
huff_encodenode_t nodes[MAX_TREE_NODES], *node_1, *node_2, *root;
uint16_t k, num_symbols, nodes_left, next_idx;
/* Initialize all leaf nodes */
num_symbols = 0;
for( k = 0; k < 256; ++ k )
if( sym[k].Count > 0 )
{
nodes[num_symbols].Symbol = sym[k].Symbol;
nodes[num_symbols].Count = sym[k].Count;
nodes[num_symbols].ChildA = (huff_encodenode_t *) 0;
nodes[num_symbols].ChildB = (huff_encodenode_t *) 0;
++ num_symbols;
}
/* Build tree by joining the lightest nodes until there is only
one node left (the root node). */
root = (huff_encodenode_t *) 0;
nodes_left = num_symbols;
next_idx = num_symbols;
while( nodes_left > 1 )
{
/* Find the two lightest nodes */
node_1 = (huff_encodenode_t *) 0;
node_2 = (huff_encodenode_t *) 0;
for( k = 0; k < next_idx; ++ k )
{
if( nodes[k].Count > 0 )
{
if( !node_1 || (nodes[k].Count <= node_1->Count) )
{
node_2 = node_1;
node_1 = &nodes[k];
}
else if( !node_2 || (nodes[k].Count <= node_2->Count) )
{
node_2 = &nodes[k];
}
}
}
/* Join the two nodes into a new parent node */
root = &nodes[next_idx];
root->ChildA = node_1;
root->ChildB = node_2;
root->Count = node_1->Count + node_2->Count;
root->Symbol = -1;
node_1->Count = 0;
node_2->Count = 0;
++ next_idx;
-- nodes_left;
}
/* Store the tree in the output stream, and in the sym[] array (the
latter is used as a look-up-table for faster encoding) */
if( root )
{
_Huffman_StoreTree( root, sym, stream, 0, 0 );
}
else
{
/* Special case: only one symbol => no binary tree */
root = &nodes[0];
_Huffman_StoreTree( root, sym, stream, 0, 1 );
}
}
/*************************************************************************
* Huffman_Compress() - Compress a block of data using a Huffman coder.
* in - Input (uncompressed) buffer.
* out - Output (compressed) buffer. This buffer must be 384 bytes
* larger than the input buffer.
* insize - Number of input bytes.
* The function returns the size of the compressed data.
*************************************************************************/
int16_t Huffman_Compress( uint8_t *in, uint8_t *out, uint16_t insize )
{
huff_sym_t sym[256], tmp;
huff_bitstream_t stream;
uint16_t k, total_bytes, swaps, symbol;
/* Do we have anything to compress? */
if( insize < 1 ) return 0;
/* Initialize bitstream */
_Huffman_InitBitstream( &stream, out );
/* Calculate and sort histogram for input data */
_Huffman_Hist( in, sym, insize );
/* Build Huffman tree */
_Huffman_MakeTree( sym, &stream );
/* Sort histogram - first symbol first (bubble sort) */
do
{
swaps = 0;
for( k = 0; k < 255; ++ k )
{
if( sym[k].Symbol > sym[k+1].Symbol )
{
tmp = sym[k];
sym[k] = sym[k+1];
sym[k+1] = tmp;
swaps = 1;
}
}
}
while( swaps );
/* Encode input stream */
for( k = 0; k < insize; ++ k )
{
symbol = in[k];
_Huffman_WriteBits( &stream, sym[symbol].Code,
sym[symbol].Bits );
}
/* Calculate size of output data */
total_bytes = (int16_t)(stream.BytePtr - out);
if( stream.BitPos > 0 )
{
++ total_bytes;
}
return total_bytes;
}
|
tinyos-io/tinyos-3.x-contrib | cotsbots/tos/lib/MotorBoard.h | /* tab:4
*
*
* "Copyright (c) 2002 and 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: 7/12/02
*
*/
/* Message types/commands */
enum {
MOTOR_TEST_START = 1,
MOTOR_TEST_STOP = 2,
LED_ON = 3,
LED_OFF = 4,
LED_TOGGLE = 5,
SET_SPEED = 6,
SET_DIRECTION = 7,
SET_TURN = 8,
ADC_READING = 9,
GET_ADC_READING = 10,
SERVO_DEBUG = 13,
SET_KP = 14,
SET_KI = 15,
SET_STRAIGHT = 16,
START_FIGURE8 = 17,
STOP_FIGURE8 = 18,
SET_SPEEDTURNDIR = 19,
GET_SERVODATA = 20,
STOP_SERVODATA = 21,
SET_TURN12 = 22,
SET_TURN34 = 23,
ACCEL_READING = 24,
START_ACCEL = 25,
STOP_ACCEL = 26,
SET_FIGURE8_SPEED = 27,
NAVIGATE = 28,
GET_KP = 29,
GET_KI = 30,
GET_STRAIGHT = 31,
MICA_LED_ON = 125,
MICA_LED_OFF = 126,
MICA_LED_TOGGLE = 127
};
enum {
OFF = 0,
FORWARD = 1,
REVERSE = 0,
STRAIGHT = 30,
};
enum {
KP_ADDR = 10,
KI_ADDR = 11,
STRAIGHT_ADDR = 12
};
enum {
MOTORMsgLength = 4,
MOTORDataLength = 2
};
/*
* MOTOR_Msg type
* addr: refers to address of motor board (the motor boards are
* designed so that they may be stacked to get more motor channels
* if necessary.
* type: type of message or command being sent -- defined above.
* data: self-explanatory
*/
typedef struct MOTOR_Msg
{
uint8_t addr;
uint8_t type;
uint8_t data[MOTORMsgLength-2];
} MOTOR_Msg;
typedef MOTOR_Msg * MOTOR_MsgPtr;
enum {
TOSM_SERVO_PORT = 0,
TOSM_ACCELX_PORT = 6,
TOSM_ACCELY_PORT = 7,
};
|
tinyos-io/tinyos-3.x-contrib | antlab-polimi/dpcm_C/quanttables.h | <reponame>tinyos-io/tinyos-3.x-contrib
/*
* Copyright (c) 2006 Stanford University.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
* - Neither the name of the Stanford University nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STANFORD
* UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @author <NAME> (<EMAIL>)
*/
#ifndef _QUANTTABLES_H_
#define _QUANTTABLES_H_
uint8_t QUANT_TABLE[] = {
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68, 109, 103, 77,
24, 35, 55, 64, 81, 104, 113, 92,
49, 64, 78, 87, 103, 121, 120, 101,
72, 92, 95, 98, 112, 100, 103, 99
};
#endif
|
tinyos-io/tinyos-3.x-contrib | rincon/apps/tests/TestLpl/TestMultipleTx/TestMulti.h |
#ifndef TESTMULTI_H
#define TESTMULTI_H
#include "message.h"
typedef nx_struct TestMultiMsg {
nx_uint8_t myData[TOSH_DATA_LENGTH];
} TestMultiMsg;
enum {
AM_TESTMULTIMSG = 0x5,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | stanford-sing/s4-tinyos-2.x/tos/lib/bvr/topology.h | <filename>stanford-sing/s4-tinyos-2.x/tos/lib/bvr/topology.h
/* This file autogenerated by generate_topology.pl. Do not edit
* Parameters: n:200 density:12 roots:5 root placement:edges seed:123
* Author: <NAME>
*/
#ifndef TOPOLOGY_H
#define TOPOLOGY_H
uint16_t TOS_LOCAL_ADDRESS=1;
enum {
N_NODES = 225,
N_ROOT_BEACONS = 8,
DIAMETER = 15,
INVALID_BEACON_ID = 0xff,
};
uint8_t hc_root_beacon_id[N_NODES] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
5, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 7, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 3, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 4, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff
};
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/quanto/tools/quanto/compression/libquantocode.h | <filename>berkeley/quanto/tools/quanto/compression/libquantocode.h
/*
* Copyright (c) 2009 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Author: <NAME> <<EMAIL>>
*
*/
#ifndef _LIBQUANTOCODE_H
#define _LIBQUANTOCODE_H
#include <stdint.h>
typedef uint8_t bool;
#define FALSE 0
#define TRUE 1
/***************** A BitBuffer *****************/
typedef struct {
uint16_t size; //size in bytes
uint16_t pos; //position in bits where to write next bit
uint16_t rpos; //position in bits where to read next bit
uint8_t buf[];
} bitBuf;
bitBuf* bitBuf_new(uint16_t size);
void bitBuf_delete(bitBuf* buf);
inline void bitBuf_clear(bitBuf* buf);
inline bool bitBuf_pad(bitBuf* buf);
inline void bitBuf_setReadPos(bitBuf* buf,uint16_t pos);
inline void bitBuf_resetReadPos(bitBuf* buf);
inline uint16_t bitBuf_getReadPos(bitBuf* buf);
/** Return the length of the bitBuf in bytes */
inline uint16_t bitBuf_length(bitBuf* buf);
inline bool bitBuf_putBit(bitBuf* buf, bool bit);
inline bool bitBuf_putByte(bitBuf* buf, uint8_t byte);
inline int bitBuf_getNextBit(bitBuf* buf);
void bitBuf_print(bitBuf* buf);
/************* 32-bit Elias Gamma Codec ***************/
/* encode */
void elias_gamma_encode(uint32_t b, bitBuf* buf);
/* Decode the next elias_gamma integer from the buffer.
* Assumes that an elias_gamma encoded integer begins in
* buf->rpos */
uint32_t elias_gamma_decode(bitBuf *buf);
/************ 32-bit Elias Delta Codec ***************/
/* Elias Delta encodes the length portion of the elias
* gamma code using elias gamma */
void elias_delta_encode(uint32_t b, bitBuf* buf);
uint32_t elias_delta_decode(bitBuf *buf);
/************ 8-bit Move To Front Codec **************/
typedef struct {
uint8_t order[256];
uint8_t h;
} mtf_encoder;
void mtf_init(mtf_encoder* mtf);
uint8_t mtf_encode(mtf_encoder* mtf, uint8_t b);
uint8_t mtf_decode(mtf_encoder* mtf, uint8_t b);
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/stargate/sfaccess/sfaccess.c | <reponame>tinyos-io/tinyos-3.x-contrib
#include <stdio.h>
#include <stdlib.h>
#include "telossource.h"
int main(int argc, char **argv)
{
int fd;
if (argc != 3)
{
fprintf(stderr, "Usage: %s <host> <port> - dump packets from a serial forwarder\n", argv[0]);
exit(2);
}
fd = open_telos_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);
}
for (;;)
{
int len, i;
const telospacket *packet = read_telos_packet(fd);
if (!packet)
exit(0);
printf("\n");
printf("length = %i\n",packet->length);
printf("dsn = %i\n",packet->dsn);
printf("addr = %i\n",packet->addr);
printf("type = %i\n",packet->type);
for (i = 0; i < packet->length; i++)
printf("%02x ", packet->data[i]);
putchar('\n');
fflush(stdout);
free((void *)packet);
}
}
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/lib/industrialCtp/routing/CtpRoutingEngine.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
*/
#ifndef CTPROUTINGENGINE_H
#define CTPROUTINGENGINE_H
/**
* TRUE if we are to use congestion in the routing engine
*/
#ifndef ECN_ON
#define ECN_ON FALSE
#endif
/**
* Minimum routing interval
*/
#ifndef CTP_MIN_BEACON_INTERVAL
#define CTP_MIN_BEACON_INTERVAL 10240U
#endif
/**
* The amount of time dedicated to network setup
* Where beacons are generated more rapidly
*/
#ifndef CTP_SETUP_DURATION
#define CTP_SETUP_DURATION 3686400U // 1 hour setup period with more beacons
#endif
/**
* The maximum beacon interval during the setup phase
*/
#ifndef CTP_SETUP_MAX_BEACON_INTERVAL
#define CTP_SETUP_MAX_BEACON_INTERVAL 614400U // 10 minutes
#endif
/**
* The maximum beacon interval after setup
*/
#ifndef CTP_MAX_BEACON_INTERVAL
#define CTP_MAX_BEACON_INTERVAL 44236800U // 12 hours
#endif
enum {
AM_TREE_ROUTING_CONTROL = 0xCE,
BEACON_INTERVAL = 30720, // Increased the minimum beacon interval
INVALID_ADDR = TOS_BCAST_ADDR,
ETX_THRESHOLD = 50, // link quality=20% -> ETX=5 -> Metric=50
PARENT_SWITCH_THRESHOLD = 15,
MAX_METRIC = 0xFFFF,
};
typedef struct {
am_addr_t parent;
uint16_t etx;
bool haveHeard;
bool congested;
} route_info_t;
typedef struct {
am_addr_t neighbor;
route_info_t info;
} routing_table_entry;
#endif
|
tinyos-io/tinyos-3.x-contrib | ethz/nodule/tos/chips/at32uc3b/at32uc3b_config.h | /* $Id: at32uc3b_config.h,v 1.2 2008/03/11 23:41:55 yuecelm Exp $ */
/* @author <NAME> <<EMAIL>> */
#ifndef __AT32UC3B_CONFIG_H__
#define __AT32UC3B_CONFIG_H__
#include "at32uc3b.h"
/* interrupt priority table (0-3, 0 means highest priority) */
#define AVR32_INTC_INTLEVEL_DEFAULT 3
#define AVR32_INTC_INTLEVEL_PM 1
#define AVR32_INTC_INTLEVEL_GPIO 3
#define AVR32_INTC_INTLEVEL_PDCA 2
#define AVR32_INTC_INTLEVEL_USART0 2
#define AVR32_INTC_INTLEVEL_USART1 2
#define AVR32_INTC_INTLEVEL_USART2 2
/* startup time of 32 KHz oscillator */
/* STARTUP clock cycles
* 0 0
* 1 128
* 2 8192
* 3 16384
* 4 65536
* 5 131072
* 6 262144
* 7 524288
*/
#define AVR32_PM_OSCCTRL32_DEFAULT_STARTUP 5
#endif /*__AT32UC3B_CONFIG_H__*/
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/chips/cc1000_sync/UniqueReceive.h |
#ifndef UNIQUERECEIVE_H
#define UNIQUERECEIVE_H
#define RECEIVE_HISTORY_SIZE 4
#endif
|
tinyos-io/tinyos-3.x-contrib | sensorscheme/tos/lib/SensorScheme/Components.h | <filename>sensorscheme/tos/lib/SensorScheme/Components.h<gh_stars>1-10
#ifndef COMPONENTS_H
#define COMPONENTS_H
#define DEF_COMPONENTS(name, pr) components pr as PR_##name;
#define SIMPLE_PRIM_CONFIG(name, pr) App.Primitive[name] -> PR_##name;
#define EVAL_PRIM_CONFIG(name, pr) App.Eval[name] -> PR_##name;
#define APPLY_PRIM_CONFIG(name, pr) App.Apply[name] -> PR_##name;
#define SEND_PRIM_CONFIG(name, pr) App.Sender[name] -> PR_##name;
#define RECEIVER_CONFIG(name, pr) App.Receiver[name] -> PR_##name;
#endif // COMPONENTS_H
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/tinyos2/nodepower.h | <filename>eon/eon/src/runtime/tinyos2/nodepower.h
#ifndef NODEPOWER_H_INCLUDED
#define NODEPOWER_H_INCLUDED
//StatePower in mW
double
getStatePower (uint8_t state, bool max)
{
int i;
double power = 0.0;
for (i = 0; i < NUMPATHS; i++)
{
if (state <= minPathState[i])
{
//good
if (max)
{
power +=
(avgPathRate[i] * getMaxPathEnergy (i, state) *
PATHRATESECONDS);
}
else
{
power +=
(avgPathRate[i] * getMinPathEnergy (i, state) *
PATHRATESECONDS);
}
//factor in wakeups
power += (avgPathRate[i] * wakeupProb[i] * WAKEPOWER * wakeTimeMS);
}
}
//factor in stargate idle power
power += (STARGATEIDLEPOWER * 1000) * stargateDutyCycle[state];
power += (IDLEPOWER * 1000);
return power;
}
uint8_t
getStateFromPower (double targetpower, float *scale)
{
int i;
uint8_t state = 0;
double minp, maxp;
for (i = NUMSTATES - 1; i > 0; i--)
{
minp = getStatePower (i, FALSE);
maxp = getStatePower (i, TRUE);
if (targetpower >= minp)
{
state = i;
break;
}
}
//figure scale
if (targetpower >= maxp)
{
*scale = 1.0;
}
else if (targetpower <= minp)
{
*scale = 0.0;
}
else
{
*scale = (targetpower - minp) / (maxp - minp);
}
return state;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/driver/vendor_request.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 vendor_class_request(libusb_device_t *dev,
int type, int recipient,
int request, int value, int index,
void *buffer, int size, int direction,
int *ret, int timeout)
{
NTSTATUS status = STATUS_SUCCESS;
URB urb;
*ret = 0;
DEBUG_PRINT_NL();
memset(&urb, 0, sizeof(struct _URB_CONTROL_VENDOR_OR_CLASS_REQUEST));
switch(type)
{
case USB_TYPE_CLASS:
DEBUG_MESSAGE("vendor_class_request(): type: class");
switch(recipient)
{
case USB_RECIP_DEVICE:
DEBUG_MESSAGE("vendor_class_request(): recipient: device");
urb.UrbHeader.Function = URB_FUNCTION_CLASS_DEVICE;
break;
case USB_RECIP_INTERFACE:
DEBUG_MESSAGE("vendor_class_request(): recipient: interface");
urb.UrbHeader.Function = URB_FUNCTION_CLASS_INTERFACE;
break;
case USB_RECIP_ENDPOINT:
DEBUG_MESSAGE("vendor_class_request(): recipient: endpoint");
urb.UrbHeader.Function = URB_FUNCTION_CLASS_ENDPOINT;
break;
case USB_RECIP_OTHER:
DEBUG_MESSAGE("vendor_class_request(): recipient: other");
urb.UrbHeader.Function = URB_FUNCTION_CLASS_OTHER;
break;
default:
DEBUG_ERROR("vendor_class_request(): invalid recipient");
return STATUS_INVALID_PARAMETER;
}
break;
case USB_TYPE_VENDOR:
DEBUG_MESSAGE("vendor_class_request(): type: vendor");
switch(recipient)
{
case USB_RECIP_DEVICE:
DEBUG_MESSAGE("vendor_class_request(): recipient: device");
urb.UrbHeader.Function = URB_FUNCTION_VENDOR_DEVICE;
break;
case USB_RECIP_INTERFACE:
DEBUG_MESSAGE("vendor_class_request(): recipient: interface");
urb.UrbHeader.Function = URB_FUNCTION_VENDOR_INTERFACE;
break;
case USB_RECIP_ENDPOINT:
DEBUG_MESSAGE("vendor_class_request(): recipient: endpoint");
urb.UrbHeader.Function = URB_FUNCTION_VENDOR_ENDPOINT;
break;
case USB_RECIP_OTHER:
DEBUG_MESSAGE("vendor_class_request(): recipient: other");
urb.UrbHeader.Function = URB_FUNCTION_VENDOR_OTHER;
break;
default:
DEBUG_ERROR("vendor_class_request(): invalid recipient");
return STATUS_INVALID_PARAMETER;
}
break;
default:
DEBUG_ERROR("vendor_class_request(): invalid type");
return STATUS_INVALID_PARAMETER;
}
DEBUG_MESSAGE("vendor_class_request(): request: 0x%02x", request);
DEBUG_MESSAGE("vendor_class_request(): value: 0x%04x", value);
DEBUG_MESSAGE("vendor_class_request(): index: 0x%04x", index);
DEBUG_MESSAGE("vendor_class_request(): size: %d", size);
if(direction == USBD_TRANSFER_DIRECTION_IN)
{
DEBUG_MESSAGE("vendor_class_request(): direction: in");
}
else
{
DEBUG_MESSAGE("vendor_class_request(): direction: out");
}
DEBUG_MESSAGE("vendor_class_request(): timeout: %d", timeout);
urb.UrbHeader.Length = sizeof(struct _URB_CONTROL_VENDOR_OR_CLASS_REQUEST);
urb.UrbControlVendorClassRequest.TransferFlags
= direction | USBD_SHORT_TRANSFER_OK ;
urb.UrbControlVendorClassRequest.TransferBufferLength = size;
urb.UrbControlVendorClassRequest.TransferBufferMDL = NULL;
urb.UrbControlVendorClassRequest.TransferBuffer = buffer;
urb.UrbControlVendorClassRequest.Request = (UCHAR)request;
urb.UrbControlVendorClassRequest.Value = (USHORT)value;
urb.UrbControlVendorClassRequest.Index = (USHORT)index;
status = call_usbd(dev, &urb, IOCTL_INTERNAL_USB_SUBMIT_URB, timeout);
if(!NT_SUCCESS(status) || !USBD_SUCCESS(urb.UrbHeader.Status))
{
DEBUG_ERROR("vendor_class_request(): request failed: status: 0x%x, "
"urb-status: 0x%x", status, urb.UrbHeader.Status);
}
else
{
if(direction == USBD_TRANSFER_DIRECTION_IN)
*ret = urb.UrbControlVendorClassRequest.TransferBufferLength;
DEBUG_MESSAGE("vendor_class_request(): %d bytes transmitted",
urb.UrbControlVendorClassRequest.TransferBufferLength);
}
return status;
}
|
tinyos-io/tinyos-3.x-contrib | blaze/tos/chips/ccxx00_single/RadioStackPacket.h |
#ifndef RADIOSTACKPACKET_H
#define RADIOSTACKPACKET_H
#include "message.h"
/** The message pointer passed around every layer in the radio stack */
message_t *RADIO_STACK_PACKET;
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libnxt/main_sambaget.c | <reponame>tinyos-io/tinyos-3.x-contrib
/**
* Main program code for the sambaget utility. Write the SAM-BA boot
* monitor program to a given file name.
*
* 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 <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.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);
}
nxt_error_t get_samba(nxt_t *nxt, char *filename)
{
FILE *fd;
int page = 0;
fd = fopen(filename, "w");
if (fd == NULL)
return NXT_FILE_ERROR;
for (page = 0; page < 32*1024; page+=4)
{
nxt_word_t w;
NXT_ERR(nxt_read_word(nxt, 0x100000+page, &w));
if(fwrite((char *)&w, 4, 1, fd) != 1)
return NXT_FILE_ERROR;
fprintf(stderr,".");
}
fprintf(stderr, "\nDONE\n");
fclose(fd);
return NXT_OK;
}
int main(int argc, char *argv[])
{
nxt_t *nxt;
nxt_error_t err;
char *fw_file;
if (argc != 2)
{
printf("Syntax: %s <filename>\n"
"\n"
"Example: %s samba.bin\n", argv[0], argv[0]);
exit(1);
}
fw_file = argv[1];
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"
"Retrieving SAM-BA monitor code...\n");
/* Retrieve the sam-ba boot code */
NXT_HANDLE_ERR(get_samba(nxt, argv[1]), nxt,
"Error trying to get SAM-BA code");
NXT_HANDLE_ERR(nxt_close(nxt), NULL,
"Error while closing connection to NXT");
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | stanford-sing/s4-tinyos-2.x/tos/lib/util/util.h | // ex: set tabstop=2 shiftwidth=2 expandtab syn=c:
// $Id: util.h,v 1.1 2008/10/23 22:22:41 genie1 Exp $
/*
* "Copyright (c) 2000-2003 The Regents of the University of California.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written agreement is
* hereby granted, provided that the above copyright notice, the following
* two paragraphs and the author appear in all copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
* OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
* CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
* Copyright (c) 2002-2003 Intel Corporation
* All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE
* file. If you do not find these files, copies can be found by writing to
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
* 94704. Attention: Intel License Inquiry.
*/
/*
* Authors: <NAME>
* Date Last Modified: 2005/05/26
*/
#ifndef _UTIL_H
#define _UTIL_H
/* Set the bth bit of integer a */
inline void set_bit(uint8_t *a, uint8_t b) {
*a |= (1 << b);
}
/* Get the bth bit of integer a */
inline bool get_bit(uint8_t a, uint8_t b) {
return (a & (1 << b))?1:0;
}
/* Reset the bth bit of a */
inline void reset_bit(uint8_t *a, uint8_t b) {
*a &= ~(1<<b);
}
/* Absolute value of x */
inline uint16_t int_abs(int16_t x) {
return (uint16_t)((x < 0)?-x:x);
}
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/support/sdk/c/blip/interface/tun_dev_cygwin.c |
#include <Windows.h>
#include <stdio.h>
#include <string.h>
#include <ddk/ntddk.h>
#include <stdint.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#define AF_INET6 23
#include <ip.h>
#include <in_cksum.h>
/* tun defs we'll need. */
#define ADAPTER_KEY "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
#define NETWORK_CONNECTIONS_KEY "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
#define TAP_ID "tap0901"
#define TAP_COMPONENT_ID TAP_ID
#define USERMODEDEVICEDIR "\\\\.\\Global\\"
#define TAPSUFFIX ".tap"
#define TAP_CONTROL_CODE(request,method) \
CTL_CODE (FILE_DEVICE_UNKNOWN, request, method, FILE_ANY_ACCESS)
#define TAP_IOCTL_GET_VERSION TAP_CONTROL_CODE (2, METHOD_BUFFERED)
#define TAP_IOCTL_SET_MEDIA_STATUS TAP_CONTROL_CODE (6, METHOD_BUFFERED)
struct tap_reg {
const char *guid;
struct tap_reg *next;
};
struct panel_reg {
char *name;
char *guid;
struct panel_reg *next;
};
/* define what is usuall in if_ether.h */
#define ETH_ALEN 6
#define ETH_P_IPV6 0x86DD
#define IPPROTO_ICMPV6 58
/* 802.3 ethernet header: not provided in cygwin */
struct ethhdr {
unsigned char h_dest[ETH_ALEN];
unsigned char h_source[ETH_ALEN];
unsigned short h_proto;
} __attribute__((packed));
/* link-layer address ICMPv6 option header */
struct icmp6_llopt_hdr {
uint8_t type;
uint8_t len;
uint8_t ll_addr[ETH_ALEN];
} __attribute__((packed));
/* for a given device id, look up the device GUID in the registry. */
char *get_tap_guid (int i) {
static char guid[256];
char *rv = NULL;
HKEY adapter_key;
LONG status;
DWORD len;
struct tap_reg *first = NULL;
struct tap_reg *last = NULL;
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
ADAPTER_KEY,
0,
KEY_READ,
&adapter_key);
if (status != ERROR_SUCCESS)
printf ("Error opening registry key: %s", ADAPTER_KEY);
do {
char enum_name[256];
char unit_string[256];
HKEY unit_key;
char component_id_string[] = "ComponentId";
char component_id[256];
char net_cfg_instance_id_string[] = "NetCfgInstanceId";
char net_cfg_instance_id[256];
char name_data[256];
DWORD name_type;
const char name_string[] = "Name";
DWORD data_type;
len = sizeof (enum_name);
status = RegEnumKeyEx(adapter_key,
i,
enum_name,
&len,
NULL,
NULL,
NULL,
NULL);
if (status == ERROR_NO_MORE_ITEMS)
break;
else if (status != ERROR_SUCCESS)
printf ("Error enumerating registry subkeys of key: %s\n",
ADAPTER_KEY);
snprintf (unit_string, sizeof(unit_string), "%s\\%s",
ADAPTER_KEY, enum_name);
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
unit_string,
0,
KEY_READ,
&unit_key);
if (status != ERROR_SUCCESS)
printf("Error opening registry key: %s\n", unit_string);
else
{
len = sizeof (component_id);
status = RegQueryValueEx(unit_key,
component_id_string,
NULL,
&data_type,
component_id,
&len);
if (status != ERROR_SUCCESS || data_type != REG_SZ)
/* printf("Error opening registry key (2): %s : %s\n", */
/* unit_string, component_id); */
;
else
{
len = sizeof (net_cfg_instance_id);
status = RegQueryValueEx(unit_key,
net_cfg_instance_id_string,
NULL,
&data_type,
net_cfg_instance_id,
&len);
if (status == ERROR_SUCCESS && data_type == REG_SZ)
{
if (!strcmp (component_id, TAP_COMPONENT_ID))
{
len = sizeof (name_data);
status = RegQueryValueEx(unit_key,
name_string,
NULL,
&name_type,
name_data,
&len);
printf("guid: %s %S\n", net_cfg_instance_id, name_data);
strncpy(guid, net_cfg_instance_id, sizeof(guid));
rv = guid;
}
}
}
RegCloseKey (unit_key);
}
} while (0);
RegCloseKey (adapter_key);
return rv;
}
/* get a list of all the devices registered in the control pannel
* we need this to get the guid/name pairs.
*/
struct panel_reg *get_panel_reg () {
LONG status;
HKEY network_connections_key;
DWORD len;
struct panel_reg *first = NULL;
struct panel_reg *last = NULL;
int i = 0;
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
NETWORK_CONNECTIONS_KEY,
0,
KEY_READ,
&network_connections_key);
if (status != ERROR_SUCCESS)
printf("Error opening registry key: %s", NETWORK_CONNECTIONS_KEY);
while (1) {
char enum_name[256];
char connection_string[256];
HKEY connection_key;
char name_data[256];
DWORD name_type;
const char name_string[] = "Name";
len = sizeof (enum_name);
status = RegEnumKeyEx(network_connections_key,
i,
enum_name,
&len,
NULL,
NULL,
NULL,
NULL);
if (status == ERROR_NO_MORE_ITEMS)
break;
else if (status != ERROR_SUCCESS)
printf("Error enumerating registry subkeys of key: %s",
NETWORK_CONNECTIONS_KEY);
snprintf (connection_string, sizeof(connection_string),
"%s\\%s\\Connection",
NETWORK_CONNECTIONS_KEY, enum_name);
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
connection_string,
0,
KEY_READ,
&connection_key);
if (status != ERROR_SUCCESS)
printf("Error opening registry key: %s", connection_string);
else
{
len = sizeof (name_data);
status = RegQueryValueEx(
connection_key,
name_string,
NULL,
&name_type,
name_data,
&len);
if (status != ERROR_SUCCESS || name_type != REG_SZ)
printf( "Error opening registry key: %s\\%s\\%s",
NETWORK_CONNECTIONS_KEY, connection_string, name_string);
else
{
struct panel_reg *reg;
reg = malloc(sizeof(struct panel_reg));
reg->name = malloc(strlen(name_data));
reg->guid = malloc(strlen(enum_name));
strcpy(reg->name, name_data);
strcpy(reg->guid, enum_name);
/* link into return list */
if (!first)
first = reg;
if (last)
last->next = reg;
last = reg;
}
RegCloseKey (connection_key);
}
++i;
}
RegCloseKey (network_connections_key);
return first;
}
/* Open a particular GUID and return a handle to it.
*/
HANDLE open_tun(char *guid, int guid_len) {
HANDLE hand = NULL;;
LONG status;
DWORD len;
int device_number;
char device_path[256];
for (device_number = 0; device_number < 100; device_number ++) {
char *device_guid = get_tap_guid(device_number);
if (device_guid) {
printf("%i: %s\n", device_number, device_guid);
if (guid)
strncpy(guid, device_guid, guid_len);
} else {
continue;
}
/* Open Windows TAP-Win32 adapter */
snprintf (device_path, sizeof(device_path), "%s%s%s",
USERMODEDEVICEDIR,
device_guid,
TAPSUFFIX);
hand = CreateFile (device_path,
GENERIC_READ | GENERIC_WRITE,
0, /* was: FILE_SHARE_READ */
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_SYSTEM, // | FILE_FLAG_OVERLAPPED,
0);
if (hand == INVALID_HANDLE_VALUE) {
hand = NULL;
printf("CreateFile failed on TAP device: %s\n", device_path);
} else
break;
device_number++;
}
if (hand) {
unsigned long info[3] = {0, 0, 0};
DeviceIoControl(hand,
TAP_IOCTL_GET_VERSION,
&info,
sizeof(info),
&info,
sizeof(info),
&len,
NULL);
if (info[0] < 9 || (info[0] == 9 && info[1] < 6)) {
printf("version: %i.%i.%i\n", info[0], info[1], info[2]);
printf("the driver has only been tested with version 9.6.0\n");
printf("aborting\n");
return NULL;
}
status = 1;
DeviceIoControl(hand,
TAP_IOCTL_SET_MEDIA_STATUS,
&status,
sizeof(status),
&status,
sizeof(status),
&len,
NULL);
}
return hand;
}
/* Send an ICMPv6 Neighbor Advertisement in response to the NS stored
in read_buf */
int send_icmp6_na(HANDLE h, char *read_buf) {
// incomming message
struct ethhdr *eh;
struct ip6_hdr *iph;
struct icmp6_hdr *icmph;
uint32_t *pad;
struct in6_addr *target;
// outgoing message
unsigned char m_buf[1280];
struct ethhdr *r_eh = (struct ethhdr *)m_buf;
struct ip6_hdr *r_iph = (struct ip6_hdr *)(r_eh + 1);
struct icmp6_hdr *r_icmph = (struct icmp6_hdr *)(r_iph + 1);
uint8_t *r_opt = (uint8_t *)(r_icmph + 1);
struct in6_addr *r_target = (struct in6_addr *)(r_opt + 4);
struct icmp6_llopt_hdr *r_llopt = (struct icmp6_llopt_hdr *)(r_target + 1);
vec_t cksum_vec[7];
uint32_t hdr[2];
DWORD len;
eh = (struct ethhdr *)read_buf;
iph = (struct ip6_hdr *)(eh + 1);
icmph = (struct icmp6_hdr *)(iph + 1);
pad = (uint32_t *)(icmph + 1);
target = (struct in6_addr *)(pad + 1);
// ethernet header
memcpy(r_eh->h_dest, eh->h_source, ETH_ALEN);
memcpy(r_eh->h_source, &target->s6_addr[8], 3);
memcpy(&r_eh->h_source[3], &target->s6_addr[13], 3);
r_eh->h_source[0] |= 0x2;
r_eh->h_proto = htons(ETH_P_IPV6);
// ip6 header
memset(r_iph, 0, sizeof(struct ip6_hdr));
r_iph->vlfc[0] = 6 << 4;
r_iph->plen = htons(sizeof(struct icmp6_hdr) + 4 +
sizeof(struct in6_addr) + sizeof(struct icmp6_llopt_hdr));
r_iph->nxt_hdr = IPPROTO_ICMPV6;
r_iph->hlim = 255;
memcpy(r_iph->ip6_src.s6_addr, target->s6_addr, 16);
memcpy(r_iph->ip6_dst.s6_addr, iph->ip6_src.s6_addr, 16);
// icmp6_hdr
r_icmph->type = ICMP_TYPE_NEIGHBOR_ADV;
r_icmph->code = 0;
r_icmph->cksum = 0;
memset(r_opt, 0, 4);
// set override, solicited flags
r_opt[0] = 0x60;
// target
memcpy(r_target->s6_addr, r_iph->ip6_src.s6_addr, 16);
// include target LL addr opt.
r_llopt->type = 2;
r_llopt->len = 1;
memcpy(r_llopt->ll_addr, r_eh->h_source, ETH_ALEN);
// fill in checksum
cksum_vec[0].ptr = (uint8_t *)(r_iph->ip6_src.s6_addr);
cksum_vec[0].len = 16;
cksum_vec[1].ptr = (uint8_t *)(r_iph->ip6_dst.s6_addr);
cksum_vec[1].len = 16;
cksum_vec[2].ptr = (uint8_t *)hdr;
cksum_vec[2].len = 8;
hdr[0] = htonl(ntohs(r_iph->plen));
hdr[1] = htonl(IPPROTO_ICMPV6);
cksum_vec[3].ptr = (uint8_t *)r_icmph;
cksum_vec[3].len = ntohs(r_iph->plen);
r_icmph->cksum = htons(in_cksum(cksum_vec, 4));
WriteFile(h, m_buf, ntohs(r_iph->plen) + sizeof(struct ip6_hdr) + sizeof(struct ethhdr), &len, NULL);
}
HANDLE tun_handle;
int tun_pipe[2];
struct panel_reg *my_device, *device_list;
unsigned char host_mac[ETH_ALEN];
DWORD WINAPI tun_forward(LPVOID arg) {
char read_buf[1500];
uint32_t u_len;
DWORD len;
while (1) {
struct ethhdr *eh;
struct ip6_hdr *iph;
struct icmp6_hdr *icmph;
int i;
ReadFile(tun_handle, read_buf, 1500, &len, NULL);
eh = (struct ethhdr *)read_buf;
iph = (struct ip6_hdr *)(eh + 1);
icmph = (struct icmp6_hdr *)(iph + 1);
if (eh->h_proto == htons(ETH_P_IPV6)) {
if (iph->nxt_hdr == IPPROTO_ICMPV6) {
if (icmph->type == ICMP_TYPE_NEIGHBOR_SOL) {
if (iph->ip6_src.s6_addr32[0] == 0 &&
iph->ip6_src.s6_addr32[1] == 0 &&
iph->ip6_src.s6_addr32[2] == 0 &&
iph->ip6_src.s6_addr32[3] == 0) {
// ignore DAD NS's
continue;
}
if (iph->ip6_dst.s6_addr[15] == 0x64)
continue;
memcpy(host_mac, eh->h_source, ETH_ALEN);
send_icmp6_na(tun_handle, read_buf);
}
}
// only forward IPv6, non-ICMP messages
u_len = len - sizeof(struct ethhdr);
write(tun_pipe[1], &u_len, 4);
write(tun_pipe[1], iph, u_len);
}
}
}
int tun_open(char *dev) {
struct panel_reg *q;
char guid[256];
tun_handle = open_tun(guid, 256);
DWORD len;
if (dev) {
*dev = '\0';
}
device_list = get_panel_reg();
for (q = device_list; q != NULL; q = q->next) {
if (!strcmp(q->guid, guid)) {
printf("%s %s\n", q->guid, q->name);
break;
}
}
my_device = q;
if (tun_handle == NULL || q == NULL) return -1;
if (pipe(tun_pipe) < 0)
return -1;
return tun_pipe[0];
}
int tun_setup(char *dev, struct in6_addr *addr, int pfxlen) {
char system_buf[256], ip_buf[256];
inet_ntop6(addr, ip_buf, 256);
if (!tun_handle) return -1;
snprintf(system_buf,
256,
"netsh interface ipv6 add address \"%s\" %s",
my_device->name,
ip_buf);
system(system_buf);
/* if (fcntl(tun_pipe[0], F_SETFL, O_NONBLOCK) < 0) { */
/* perror("O_NONBLOCK"); */
/* } */
CreateThread(NULL, 0, tun_forward, NULL, 0, NULL);
return 0;
}
int tun_write(int fd, struct split_ip_msg *msg) {
uint8_t buf[INET_MTU + sizeof(struct ethhdr)], *packet;
struct ethhdr *eh = (struct ethhdr *)buf;
struct generic_header *cur;
packet = (uint8_t *)(eh + 1);
DWORD write_len;
if (ntohs(msg->hdr.plen) + sizeof(struct ip6_hdr) >= INET_MTU)
return -1;
memcpy(eh->h_source, host_mac, ETH_ALEN);
memcpy(eh->h_source, &msg->hdr.ip6_src.s6_addr[8], 3);
memcpy(&eh->h_source[3], &msg->hdr.ip6_src.s6_addr[13], 3);
eh->h_source[0] |= 0x2;
eh->h_proto = htons(ETH_P_IPV6);
memcpy(packet, &msg->hdr, sizeof(struct ip6_hdr));
packet += sizeof(struct ip6_hdr);
cur = msg->headers;
while (cur != NULL) {
memcpy(packet, cur->hdr.data, cur->len);
packet += cur->len;
cur = cur->next;
}
memcpy(packet, msg->data, msg->data_len);
if (WriteFile(tun_handle, buf, sizeof(struct ethhdr) + sizeof(struct ip6_hdr) + ntohs(msg->hdr.plen),
&write_len, NULL))
return 0;
else
return -1;
}
int tun_read(int fd, char *buf, int len) {
uint32_t pkt_len, current_read = 0;
int read_len;
read_len = read(fd, &pkt_len, 4);
if (read_len <= 0) {
return 0;
} else if (read_len != 4) {
printf("SHORT READ: %i!\n", read_len);
return 0;
}
if (pkt_len > len) {
printf("NOT ENOUGH BUFFER\n");
return 0;
}
while (current_read < pkt_len) {
current_read += read(fd, buf + current_read, pkt_len - current_read);
}
return current_read;
}
int main() {
int tun_fd;
struct in6_addr l_addr;
char buf[1500];
inet_pton6("fdf8:f53e:61e4::18", &l_addr);
tun_fd = tun_open(NULL);
tun_setup(NULL, &l_addr, 64);
while (1) {
uint32_t len, i;
len = tun_read(tun_fd, buf, 1500);
printf("read: len: %i\n", len);
for (i = 0; i < len; i++) {
printf("%hhx ", buf[i]);
}
printf("\n");
}
}
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/chips/cc1000_sync/CC1000Sync.h | <filename>rincon/tos/chips/cc1000_sync/CC1000Sync.h
#ifndef CC1000SYNC_H
#define CC1000SYNC_H
enum {
SYNC_NUM_TIMERS = 5,
SYNC_NUM_NEIGHBORS = 7,
LIFE_INCREMENT = 32,
LIFE_DECREMENT = 1,
/*
* PREEMPTIVE_DELAY is the number of microseconds before the next receive
* check to start sending the message. Ideally, it should be about the
* same amount of time to send a full message, plus some padding.
* Too high, and you'll send the message too early which wastes energy.
* Too low, and you could send the message too late, which really wastes
* energy. Err on the side of too high. Keep in mind clock skew and
* algorithm munching.
*/
PREEMPTIVE_DELAY = 50,
};
/**
* List of neighbors and whether or not they're valid.
* There are two extra entries than the number of timers we have
* available, to help distribute the timers to the most active addresses
*/
typedef struct SyncNeighbor {
am_addr_t address;
uint8_t life;
bool isValid;
bool isQueued;
} SyncNeighbor;
/**
* Timer slot to keep track of which timer runs which synchronization send
*/
typedef struct TimerSlot {
SyncNeighbor *neighbor;
} TimerSlot;
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/stargatehelper/fluxhandler.h | <reponame>tinyos-io/tinyos-3.x-contrib
#ifndef FLUXHANDLER_H_INCLUDED
#define FLUXHANDLER_H_INCLUDED
//#include "rt_structs.h"
#include "MemAlloc.h"
//bool isReadyByID (EdgeIn * edge);
//result_t callEdge (EdgeIn * e);
//result_t adjustIntervals();
task void FinishRecoverTask();
//result_t getOutSize (EdgeIn * e);
result_t handle_error (uint16_t nodeid, Handle indata, uint8_t error);
/*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
/*enum {
ASLEEP =0,
SLEEPY =1,
AWAKE =3,
WAKING =4,
};
int remoteCstate = ASLEEP;
*/
bool __get_bit_lock_value(uint16_t node_id)
{
int byte_idx, bit_idx;
byte_idx = node_id / 8;
bit_idx = node_id % 8;
return ((__node_locks[byte_idx] >> bit_idx) & 0x01);
}
bool __set_bit_lock_value(uint16_t node_id, bool value)
{
int byte_idx, bit_idx;
uint8_t mask;
byte_idx = node_id / 8;
bit_idx = node_id % 8;
mask = (0x01 << bit_idx);
if (value)
{
__node_locks[byte_idx] = (__node_locks[byte_idx] | mask);
} else {
__node_locks[byte_idx] = (__node_locks[byte_idx] & (~mask));
}
return value;
}
bool __try_node_lock(uint16_t node_id)
{
bool set = FALSE;
atomic {
if (__get_bit_lock_value(node_id) == FALSE)
{
__set_bit_lock_value(node_id,TRUE);
set = TRUE;
}
} //atomic
return set;
}
bool __release_node_lock(uint16_t node_id)
{
atomic {
__set_bit_lock_value(node_id, FALSE);
}
return TRUE;
}
event result_t RTClockTimer.fired()
{
atomic rt_clock++;
return SUCCESS;
}
event result_t EvalTimer.fired()
{
call IEval.reeval_energy_level();
return SUCCESS;
}
event result_t SGSleepTimer.fired()
{
TOSH_CLR_INT0_PIN();
return SUCCESS;
}
event result_t SGStatusTimer.fired()
{
return SUCCESS;
}
event result_t SGStateTimer.fired()
{
int intgrade;
intgrade = (int)(curgrade * 100);
__rt_send_buf.data[0] = curstate;
__rt_send_buf.data[1] = intgrade;
if (call StateSend.send(TOS_UART_ADDR, 2, &__rt_send_buf ) != SUCCESS)
{
call Leds.redToggle();
}
return SUCCESS;
}
event result_t SGCardTimer.fired()
{
TOSH_SET_INT0_PIN();
return SUCCESS;
}
event result_t StateSend.sendDone(TOS_MsgPtr msg, result_t success)
{
return SUCCESS;
}
event TOS_MsgPtr PathRecv.receive (TOS_MsgPtr msg)
{
result_t res;
int32_t penergy;
bool start = msg->data[0];
int id = msg->data[1];
int path = msg->data[2];
if (start)
{
//starting a flow
call IEnergyMap.startPath(id);
} else {
//ending a flow
res = call IEnergyMap.getPathEnergy(id, &penergy);
call IEval.reportPathDone(path, curstate, penergy);
}
return msg;
}
event TOS_MsgPtr SleepRecv.receive (TOS_MsgPtr msg)
{
call SGCardTimer.start(TIMER_REPEAT, (2L * 1024L));
call SGSleepTimer.start(TIMER_REPEAT, (25L * 1024L));
call SGStateTimer.start(TIMER_REPEAT, (34L * 1024L));
return msg;
}
event result_t IEval.reeval_done(uint8_t state, double grade)
{
curstate = state;
curgrade = grade;
//adjustIntervals();
return SUCCESS;
}
/************************************
*
* EDGE Consumer/Producer functions
*
************************************/
/*
task void
LocalConsumerTask ()
{
uint16_t result;
uint16_t delay, ready;
uint16_t outsize;
EdgeIn edge;
bool edgefailed;
delay = FALSE;
result = dequeue (&moteQ, &edge);
if (result == TRUE)
{
//Got an edge
//is it ready
ready = isReadyByID (&edge);
if (!ready)
{
//not ready, put it to the back of the queue
//deadlocked_edge_id = edge.node_id;
//drop the flow.
if (call BAlloc.free((Handle)edge.invar) == FAIL)
{
call Leds.redToggle();
}
//call BAlloc.free((Handle)edge.outvar);
//should probably do some error handling here
}
else
{
edgefailed = FALSE;
outsize = getOutSize (&edge);
if (outsize == 0)
{
edgefailed = TRUE;
} else {
result = call BAlloc.allocate ((HandlePtr) &(edge.outvar), outsize);
if (result == FAIL)
{
edgefailed = TRUE;
}
}
if (edgefailed)
{
__release_node_lock (edge.node_id);
handle_error (edge.node_id, (Handle) edge.invar, ERR_NOMEMORY);
} else {
call PowerDisable(); //no power management in nodes
result = callEdge(&edge);
if (result == FAIL)
{
call PowerEnable();
__release_node_lock (edge.node_id);
call BAlloc.free((Handle)edge.outvar);
handle_error (edge.node_id, (Handle) edge.invar, ERR_NOMEMORY);
}
}
} //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;
}
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;
__rtstate.batt_reserve = BATTERY_CAPACITY/2;
if (__rtstate.save_flag != 0xDEAD)
{
__rtstate.batt_reserve = 0;
//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.srcprob[j] = 0;
}
//initialize path energy
for (i=0; i < NUMPATHS; i++)
{
__rtstate.pathenergy[i] = -1;
}
}
}
event result_t PageEEPROM.readDone(result_t res)
{
post FinishRecoverTask();
return SUCCESS;
}
/*
Runtime data recovery functions
*/
result_t recoverRunTimeData()
{
//Restore runtime data
/*call IFlash.read((void*)IFLASH_SRCPROB_ADDR, srcprob, sizeof(srcprob));
call IFlash.read((void*)IFLASH_PATHPROB_ADDR, prob, sizeof(prob));
call IFlash.read((void*)IFLASH_PATHENERGY_ADDR, pathenergy, sizeof(pathenergy));
call IFlash.read((void*)IFLASH_HISTORYIDX_ADDR, &load_history_index, sizeof(load_history_index));
call IFlash.read((void*)IFLASH_LOADHISTORY_ADDR, load_history, sizeof(load_history));
call IFlash.read((void*)IFLASH_BATTERY_ADDR, &batt_reserve, sizeof(batt_reserve));*/
save_retries = 0;
post ReadStateTask();
return SUCCESS;
}
event result_t RecoverTimer.fired ()
{
recoverRunTimeData();
return SUCCESS;
}
/*task void SaveSrcProbTask()
{
save_state = STATE_SRC_PROB;
if (PageEEPROM.write(SAVE_PAGE, IFLASH_SRCPROB_ADDR, srcprob, sizeof(srcprob)) != SUCCESS)
{
if (check_retry()) post SaveSrcProbTask();
}
}
task void SaveProbTask()
{
save_state = STATE_PROB;
if (PageEEPROM.write(SAVE_PAGE, IFLASH_PATHPROB_ADDR, prob, sizeof(prob)) != SUCCESS)
{
if (check_retry()) post SaveProbTask();
}
}
task void SavePathEnergyTask()
{
save_state = STATE_PATH_ENERGY;
if (PageEEPROM.write(SAVE_PAGE, IFLASH_PATHENERGY_ADDR, pathenergy, sizeof(pathenergy)) != SUCCESS)
{
if (check_retry()) post SavePathEnergyTask();
}
}
task void SaveLoadIdxTask()
{
save_state = STATE_LOAD_IDX;
if (PageEEPROM.write(SAVE_PAGE, IFLASH_LOADHISTORYIDX_ADDR, &load_history_index, sizeof(load_history_index)) != SUCCESS)
{
if (check_retry()) post SaveLoadIdxTask();
}
}
task void SaveLoadTask()
{
save_state = STATE_LOAD;
if (PageEEPROM.write(SAVE_PAGE, IFLASH_LOADHISTORY_ADDR, load_history, sizeof(load_history)) != SUCCESS)
{
if (check_retry()) post SaveLoadTask();
}
}
task void SaveBatteryTask()
{
save_state = STATE_BATTERY;
if (PageEEPROM.write(SAVE_PAGE, IFLASH_BATTERY_ADDR, &batt_reserve, sizeof(batt_reserve)) != SUCCESS)
{
if (check_retry()) post SaveBatteryTask();
}
}
task void SaveFlagTask()
{
save_state = STATE_FLAG;
if (PageEEPROM.write(SAVE_PAGE, IFLASH_RT_ADDR, &save_flag, sizeof(save_flag)) != SUCCESS)
{
if (check_retry()) post SaveFlagTask();
}
}*/
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 result_t SaveTimer.fired ()
{
//Save runtime data
__rtstate.save_flag = 0xDEAD;
save_retries = 0;
post EraseTask();
return SUCCESS;
}
event result_t PageEEPROM.writeDone(result_t res)
{
if (res == SUCCESS)
{
save_retries = 0;
post FlushPageTask();
}
else if (check_retry())
{
post SaveTask();
}
return (SUCCESS);
}
event result_t PageEEPROM.flushDone(result_t res)
{
//We made it! Yeah!
return (SUCCESS);
}
event result_t PageEEPROM.eraseDone(result_t res)
{
if (res == SUCCESS)
{
post SaveTask();
} else if (check_retry())
{
post EraseTask();
}
return (SUCCESS);
}
event result_t PageEEPROM.syncDone(result_t result)
{
return (SUCCESS);
}
event result_t PageEEPROM.computeCrcDone(result_t result, uint16_t crc)
{
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;
/*queue_ptr = q;
atomic
{
result = enqueue (q, edge);
if (result && localCAlive == FALSE)
{
localCAlive = TRUE;
post LocalConsumerTask ();
}
}*/ //atomic
return SUCCESS;
}
#ifdef RUNTIME_TEST
event result_t SendMsg.sendDone(TOS_MsgPtr msg, result_t success)
{
return SUCCESS;
}
#endif
/********************************
* AUX functions
********************************/
uint16_t
getNextSession ()
{
uint16_t nextid;
atomic
{
nextid = session_id;
session_id++;
}
return nextid;
}
result_t handle_exit (Handle data)
{
uint32_t penergy;
result_t res;
GenericNode **ndata = (GenericNode **) data;
res = call IEnergyMap.getPathEnergy((*ndata)->_pdata.sessionID, &penergy);
if (res == FAIL)
{
penergy = 0xFFFFFFFF;
}
#ifdef RUNTIME_TEST
memcpy(__rt_send_buf.data, &((*ndata)->_pdata.weight), sizeof(uint16_t));
memcpy(__rt_send_buf.data + 2, &penergy, sizeof(uint32_t));
memcpy(__rt_send_buf.data + 6, &((*ndata)->_pdata.sessionID), sizeof(uint16_t));
if (SUCCESS == call SendMsg.send(TOS_BCAST_ADDR, 8, &__rt_send_buf ))
{
//call Leds.redToggle();
}
#endif
//report path completion
call IEval.reportPathDone((*ndata)->_pdata.weight, curstate, penergy);
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;
//put it on the queue
//Copy src contents to new edge
((GenericNode *) (*hin))->_pdata.weight += edgewt;
newedge.node_id = nodeid;
newedge.invar = (uint8_t **) hin;
//newedge.outvar = (uint8_t **) hout;
if (!dolocalenqueue (&moteQ, newedge))
{
//queue is full
return handle_error (nodeid, hin, ERR_QUEUE);
}
return SUCCESS;
}
*/
/*
//CODE FOR HANDLING EDGES FROM SOURCES TO 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);
alloc_size = call BAlloc.freeBytes ();
result = call BAlloc.allocate (&hin, datasize);
if (result == FAIL)
{
//error handling code
//call Leds.redToggle();
deadlocked_edge_id = 0xe0;
return handle_error (nodeid, outdata, ERR_NOMEMORY);
}
memcpy (*hin, *outdata, datasize);
call IEnergyMap.startPath(session);
//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 (!dolocalenqueue (&moteQ, newedge))
{
//queue is full
deadlocked_edge_id = 0xe1;
return handle_error (nodeid, hin, ERR_QUEUE);
}
deadlocked_edge_id = 0xe2;
return SUCCESS;
}
*/
#endif
|
tinyos-io/tinyos-3.x-contrib | ethz/snpk/tos/lib/net/TimeSync/TimeSyncMsg.h | /*
* Copyright (c) 2007, ETH Zuerich
* All rights reserved.
* Author: <NAME>
*/
#ifndef TIMESYNCMSG_STRUCT
#define TIMESYNCMSG_STRUCT
typedef nx_struct TimeSyncMsg
{
nx_uint16_t rootID; // the node id of the synchronization root
nx_uint8_t seqNum; // sequence number for the root
nx_int32_t offsetAverage;
nx_uint32_t localAverage;
nx_int8_t skewInt;
nx_uint32_t skewFloat;
nx_uint32_t sendingTime; // the local time when the message is prepared for sending
nx_uint16_t dummyOffset; // the real local time when the message is sent
} TimeSyncMsg;
enum {
AM_TIMESYNCMSG = 0xEE,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | intelmote2/tools/platforms/intelmote2/jflashmm/src/Jflash.h | <gh_stars>1-10
/******************************************************************************
**
** COPYRIGHT (C) 2000, 2001, 2002 Intel Corporation.
**
** The information in this file is furnished for informational use
** only, is subject to change without notice, and should not be construed as
** a commitment by Intel Corporation. Intel Corporation assumes no
** responsibility or liability for any errors or inaccuracies that may appear
** in this document or any software that may be provided in association with
** this document.
**
** FILENAME: Jflash.h
**
** PURPOSE: General header for the Jflash utility
**
** LAST MODIFIED: $Modtime: 2/27/03 11:34a $
******************************************************************************/
#include<string.h>
#define VERSION_MAX_LENGTH 11
char VERSION[VERSION_MAX_LENGTH] = {"5.01.003"};
enum CABLE_TYPES // The different cable types Jflash currently supports
{
Insight_Jtag,
Parallel_Jtag,
Wiggler_Jtag
};
#define LPT1 0x3bc // hardware base address for parallel port
#define LPT2 0x378 // the search order is LPT1 then 2 then 3
#define LPT3 0x278 // first valid address found is used (re-order if needed for multiple ports)
#define READ 0 // Flags used to modify the SA-1110 JTAG chain data depending on
#define WRITE 1 // the access mode of the Flash Memory
#define SETUP 2
#define HOLD 3
#define RS 4
#define K3 5 // Added for Bulverde/Dimebox
#define ENABLE 1
#define DISABLE 0
#define DRIVE 0
#define HIZ 1 // high Z (impedance)
#define IGNORE_PORT 0 // Flag used when accessing the parallel port
#define READ_PORT 1 // READ_PORT = 'read port', IGNORE_PORT = 'ignore port',
// using IGNORE_PORT will speed access
#define IP IGNORE_PORT
#define RP READ_PORT
#define CONTINUE 0 // not the last instruction
#define TERMINATE 1 // this is the last instruction, so go to EXIT-1 IR
#define MAX_IN_LENGTH _MAX_PATH // max length for user input strings
#define STATUS_UPDATE 2 // time between updates of program/verify status in seconds
#define FIRST_HALF_WORD_MASK 0x0000FFFF
|
tinyos-io/tinyos-3.x-contrib | tub/apps/PacketSniffer_802_15_4/sniff802154.h | #ifndef SNIFF802154_H
#define SNIFF802154_H
enum {
AM_CONTROL_PKT_T = 215, /* AM id for Serial packet containing control information as payload (i.e. #channel) */
};
typedef nx_struct control_pkt_t {
nx_uint8_t channel; /* which channel to listen on */
} control_pkt_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/tinyos2/fluxsourcepredictor.h | #ifndef FLUXSOURCEPREDICTOR_H_INCLUDED
#define FLUXSOURCEPREDICTOR_H_INCLUDED
void update_source
int32_t predict_source (uint8_t hours)
{
return 5; //TODO come back to this
}
#endif
|
tinyos-io/tinyos-3.x-contrib | wsu/telosw/ADC/WakeupADC.h | #ifndef __WAKEUPADC_H__
#define __WAKEUPADC_H__
enum{
ADDR_BYTE = 0x58
};
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/apps/turtle_snapper/impl/mica2dot/userstructs.h | <filename>eon/apps/turtle_snapper/impl/mica2dot/userstructs.h
#ifndef USERSTRUCTSH_H_INCLUDED
#define USERSTRUCTSH_H_INCLUDED
#include "gps.h"
#include "SingleStream.h"
#include "AM.h"
#include "uservariables.h"
enum
{
AM_BEACONMSG = 4,
AM_INTERESTEDMSG = 5,
AM_ACK_MSG = 6,
AM_ACK_MSG_ACK = 8,
AM_OFFERMSG = 9,
AM_OFFERACK = 10,
AM_DATAMSG = 11,
AM_DATAACK = 12,
//NOTE: Eeach command has unique ID (seq num)
AM_BEGIN_TRAVERSAL_MSG = 17,
AM_GO_NEXT_MSG = 18,
AM_GET_NEXT_CHUNK = 19,
AM_GET_BUNDLE_MSG = 20,
AM_DELETE_BUNDLE_MSG = 21,
AM_DELETE_ALL_BUNDLES_MSG = 22,
AM_END_DATA_COLLECTION_SESSION = 23,
AM_BUNDLE_INDEX_ACK = 24,
AM_RADIO_HI_POWER = 25,
AM_RADIO_LO_POWER = 26,
AM_DEADLOCK_MSG = 27,
AM_DELETE_ALL_ACK = 28,
};
typedef struct BeaconMsg
{
uint8_t version_num;
uint16_t src_addr;
} BeaconMsg_t;
typedef struct OfferMsg
{
uint16_t src_addr;
uint16_t turtle_addr;
uint16_t bundle;
uint8_t offerid;
} OfferMsg_t;
typedef struct OfferAck
{
uint16_t src_addr;
uint16_t turtle_addr;
uint16_t bundle;
uint8_t offerid;
uint8_t ok;
} OfferAck_t;
typedef struct InterestedMsg
{
uint16_t src_addr;
} InterestedMsg_t;
typedef struct InterestedAck
{
uint16_t src_addr;
}InterestedAck_t;
typedef struct AckArrayPacket{
uint16_t src_addr;
int16_t packet_num;
uint16_t packet_total;
uint16_t turtle_addr;
uint8_t start;
uint8_t end;
}AckArrayPacket_t;
typedef struct AckArrayAck{
uint16_t src_addr;
int16_t packet_num;
}AckArrayAck_t;
#define DATA_MSG_HDR_LEN 6
#define DATA_MSG_DATA_LEN (TOSH_DATA_LENGTH-DATA_MSG_HDR_LEN)
#define MAX_CONSECUTIVE_DATA_TIMEOUTS 5
#define RECV_MSG_TIMEOUT_MS 1000
#define INTERESTED_ROUNDS 3
#define INTERESTED_INTERVAL 1000
#define SEND_TIMEOUT_MS 1000
#define MAX_CONSECUTIVE_TIMEOUTS 5
#define RECV_ACK_TIMEOUT_MS 1000
#define BUNDLE_ACK_HEADER_LENGTH 6
#define BUNDLE_ACK_DATA_LENGTH TOSH_DATA_LENGTH - BUNDLE_ACK_HEADER_LENGTH
typedef struct DataMsg
{
uint16_t src_addr;
uint8_t offerid;
unsigned int last : 1;
unsigned int length : 7;
uint16_t sequence;
uint8_t data[DATA_MSG_DATA_LEN];
}DataMsg_t;
typedef struct DataAck
{
uint16_t src_addr;
uint8_t offerid;
uint16_t sequence;
}DataAck_t;
typedef struct GpsData {
char date[NMEA_CHARS_PER_FIELD]; //ddmmyy
char time[NMEA_CHARS_PER_FIELD];//hhmmss.ss
GpsFixData fix;
} GpsData_t;
typedef struct Bundle {
stream_t stream;
uint16_t turtle_num;
uint16_t bundle_num;
} Bundle_t;
/*
//NOTE: Eeach command has unique ID (seq num)
AM_BEGIN_TRAVERSAL_MSG = 17,
AM_GO_NEXT_MSG = 18
AM_GET_BUNDLE_MSG = 19,
AM_DELETE_BUNDLE_MSG_ACK = 20,
AM_BUNDLE_INDEX_ACK
*/
/*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;
uint16_t bundle;
} GetBundleMsg_t;
typedef struct DeleteBundleMsg {
uint16_t src_addr;
uint16_t bundle;
} DeleteBundleMsg_t;
typedef struct DeleteAllBundlesMsg {
uint16_t src_addr;
} DeleteAllBundlesMsg_t;
typedef struct BundleIndexAck
{
uint16_t src_addr;
uint16_t bundle;
uint8_t chunk;
uint8_t flags; //x,x,x,x,x,x,success,end
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;
//???What are these for?
stream_t g_rt_stream;
TOS_Msg g_deadlock_msg;
#endif // NODES_H_INCLUDED
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/compression/lz77/lz77_decomp.c | <gh_stars>1-10
/**************************************************************************
*
* lz77_decomp.c
*
* The LZ77 decompression algorithm.
*
* This file is licensed under the GNU GPL.
*
* (C) 2005, <NAME> <<EMAIL>>
*
*/
#include "lz77.h"
#include <inttypes.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include "../buffer.h"
uint8_t membuffer[MEMBUFSIZE];
uint8_t *data;
uint8_t read_count;
uint16_t buffer;
int lengths[33];
int offsets[2000];
void init_comp()
{
memset(lengths, 0, sizeof(lengths));
memset(offsets, 0, sizeof(offsets));
}
void end_comp()
{
int i;
printf("Lengths:\n");
for (i = 0; i < 33; i++) {
printf("%02d: %d\n", i, lengths[i]);
}
printf("Offsets:\n");
for (i = 0; i < 1501; i++) {
printf("%04d: %d\n", i, offsets[i]);
}
}
static uint8_t read_bits(uint8_t len)
{
assert(len <= 8);
uint8_t res;
// Fill the buffer
while (read_count < len) {
buffer <<= 8;
buffer |= *data++;
read_count += 8;
}
res = (buffer >> (read_count - len)) & ((1 << len) - 1);
read_count -= len;
buffer &= (1 << read_count) - 1;
return res;
}
uint16_t bits_left()
{
uint16_t res = MEMBUFSIZE - (data - membuffer); // Amount of unread data;
res *= 8;
res += read_count; // Bits read, but not outputted yet.
return res;
}
#define SEARCH_SIZE WINDOW_SIZE
uint8_t window[SEARCH_SIZE];
uint8_t *search_end;
void fill_buffer()
{
#ifdef DEBUG
fprintf(stderr, "**Filling buffer\n");
#endif
if (fread(membuffer, MEMBUFSIZE, 1, stdin) != 1) {
fprintf(stderr, "Error reading from stdin: %s\n",
strerror(errno));
exit(1);
}
read_count = 0;
buffer = 0;
data = membuffer;
}
uint16_t cyclic_difference(uint8_t *start, uint8_t *end)
{
if (start > end) {
end += SEARCH_SIZE;
}
return end - start;
}
uint8_t *cyclic_adjust(uint8_t *v)
{
if (v < window) {
v += SEARCH_SIZE;
} else if (v >= window + SEARCH_SIZE) {
v -= SEARCH_SIZE;
}
assert(v < window + SEARCH_SIZE && v >= window);
return v;
}
void insert_into_buffer(uint8_t b)
{
assert(search_end >= window && search_end < window + SEARCH_SIZE);
*search_end = b;
search_end = cyclic_adjust(search_end + 1);
// fprintf(stderr, "Buffer contains %d elements\n",
// cyclic_difference(search_start, search_end));
}
uint8_t match_length = 0;
uint8_t *match_pos;
uint8_t *orig_match_pos;
int max_length = 0;
#ifdef DEBUG
void output_match(uint8_t *pos, uint8_t len)
{
int i;
fprintf(stderr, "@%p (window starts @ %p): ", pos, window);
for (i = 0; i < len; i++) {
fprintf(stderr, "%02x", *pos);
pos = cyclic_adjust(pos + 1);
}
fprintf(stderr, "\n");
}
#endif
uint8_t get_byte()
{
if (match_length) {
uint8_t tmp;
if (match_pos == search_end) {
match_pos = orig_match_pos;
}
tmp = *match_pos;
match_pos = cyclic_adjust(match_pos + 1);
insert_into_buffer(tmp);
match_length--;
return tmp;
} else {
uint8_t tmp;
if (bits_left() < OFFSET_BITS + LENGTH_BITS + 1)
fill_buffer();
tmp = read_bits(1);
if (tmp) {
/* This was a single byte. */
uint8_t res = read_bits(8);
insert_into_buffer(res);
#ifdef DEBUG
fprintf(stderr, "Reading single byte %d\n", (int)res);
#endif
lengths[0]++;
offsets[0]++;
return res;
} else {
uint16_t offset;
offset = (uint16_t) read_bits(OFFSET_BITS - 8) << 8;
offset |= read_bits(8);
offsets[offset]++;
match_length = read_bits(LENGTH_BITS);
if (match_length == (1 << LENGTH_BITS) - 1) {
max_length++;
}
lengths[match_length + 1]++;
orig_match_pos = match_pos = cyclic_adjust(search_end - offset);
#ifdef DEBUG
fprintf(stderr, "Read offset %d and length %d. Values: ", offset,
match_length);
output_match(match_pos, match_length + 1);
#endif
tmp = *match_pos;
match_pos = cyclic_adjust(match_pos + 1);
insert_into_buffer(tmp);
return tmp;
}
}
}
int decompress_sample(int16_t *digi_x, int16_t *digi_y,
int16_t *digi_z, uint16_t *analog_x,
uint16_t *analog_y)
{
static int first = 1;
#ifdef DIFFERENCE
static int16_t last_vals[3];
int i;
#endif
if (first) {
first = 0;
fill_buffer();
search_end = window;
#ifdef DIFFERENCE
for (i = 0; i < 3; i++) {
last_vals[i] = (get_byte() << 8) | get_byte();
}
} else {
for (i = 0; i < 3; i++) {
last_vals[i] += (get_byte() << 8) | get_byte();
}
#endif
}
#ifdef DIFFERENCE
*digi_x = last_vals[0];
*digi_y = last_vals[1];
*digi_z = last_vals[2];
#else
*digi_x = (get_byte() << 8) | get_byte();
*digi_y = (get_byte() << 8) | get_byte();
*digi_z = (get_byte() << 8) | get_byte();
#endif
return max_length;
}
|
tinyos-io/tinyos-3.x-contrib | mts4x0/tos/sensorboards/mts400/mts400.h |
/******************************************************************************/
/* 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. */
/* */
/* Written and (c) by INRIA, <NAME> */
/* Contact <<EMAIL>> for comment, bug reports */
/* and possible alternative licensing of this program */
/******************************************************************************/
/**
* @file mts400.h
* @author <NAME>
* @date Fri May 9 02:30:49 2008
*
* @brief this inlude file contains declarations for the mts4X0 boards
*
*/
#ifndef MTS400_H
#define MTS400_H
// addresses of the two swtches on the i2c bus
enum{
I2C_POWER_SWITCH_ADDR=0x48,
I2C_DATA_SWITCH_ADDR=0x49,
};
// power switch
enum{
PWR_GPS_ENA = 0x80,
PWR_GPS_PWR = 0x40,
PWR_PRESSURE= 0x04,
ALLOFF=0,
ALLON=0,
// values according to the datasheet not tested
// please report sucess /failure ...
PWR_ACCEL = 0x20,
PWR_EEPROM = 0x10,
PWR_LIGHT = 0x01,
PWR_HUMIDITY= 0x08,
};
// data switch
// Bit positions;
enum{
GPS_RX_BITPOS=0,
GPS_TX_BITPOS=1,
PRESSURE_SCLK_BITPOS=2,
PRESSURE_DIN_BITPOS=3,
PRESSURE_DOUT_BITPOS=4,
// D6 not connected
HUMIDITY_SCK_BITPOS=6,
HUMIDITY_DATA_BITPOS=7,
};
// word values
enum{
GPS_RX= (1<<GPS_RX_BITPOS),
GPS_TX= (1<<GPS_TX_BITPOS),
PRESSURE_SCLK= (1<<PRESSURE_SCLK_BITPOS),
PRESSURE_DIN = (1<<PRESSURE_DIN_BITPOS),
PRESSURE_DOUT= (1<<PRESSURE_DOUT_BITPOS),
HUMIDITY_SCK = (1<<HUMIDITY_SCK_BITPOS),
PRESSURE_DATA= (1<<HUMIDITY_DATA_BITPOS),
};
#endif /* MTS400_H */
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/daq/test.c | <reponame>tinyos-io/tinyos-3.x-contrib<filename>diku/common/tools/daq/test.c
#include <stdio.h>
#include "daq_lib.h"
int main(int argc, char *argv[])
{
daq_card_t daq;
uint16_t sample;
if (argc != 2) {
fprintf(stderr, "Too few arguments\n");
return 1;
}
if (daq_open(argv[1], &daq)) {
perror("Error opening daq device");
return 1;
}
if (daq_config_channel(&daq, 0, DG_1, DR_BIPOL5V)) {
perror("Error setting channel");
return 1;
}
if (daq_get_sample(&daq, &sample)) {
perror("Error getting sample");
return 1;
}
printf("Sample returned: %04x\n", sample);
if (daq_close(&daq)) {
perror("Error closing daq device");
return 1;
}
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/motelog/sunlog.h | enum { MY_FLASH_REGION_ID = unique("ByteEEPROM") };
|
tinyos-io/tinyos-3.x-contrib | wsu/tools/simx/simx/lib/simx/sync/sync.h | #ifndef SIMX_SYNC_H_INCLUDE
#define SIMX_SYNC_H_INCLUDE
#include <sim_tossim.h>
class SimxSync {
public:
SimxSync();
~SimxSync();
int waitUntilNextEvent(long max_wait_msec);
int runNextEventInTime();
int runNextEvent();
sim_time_t simTime();
sim_time_t realTime();
void synchronize();
void setClockMul(float clock_mul);
float getClockMul();
void setStopAt(long long int stop_at);
long long int getStopAt();
void setMaxWait(long max_wait);
long getMaxWait();
private:
long max_wait_msec;
};
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/tos/platforms/nxtmote/Board.h | /*----------------------------------------------------------------------------
* ATMEL Microcontroller Software Support - ROUSSET -
*----------------------------------------------------------------------------
* The software is delivered "AS IS" without warranty or condition of any
* kind, either express, implied or statutory. This includes without
* limitation any warranty or condition with respect to merchantability or
* fitness for any particular purpose, or against the infringements of
* intellectual property rights of others.
*----------------------------------------------------------------------------
* File Name : Board.h
* Object : AT91SAM7S Evaluation Board Features Definition File.
*
* Creation : JPP 16/Jun/2004
* V 1.0 21/Feb/05 JPP : Define __ramfunc
* V 1.1 21/Feb/05 JPP : add Lib definition
* V 1.2 22/Feb/05 JPP : Add DBGU inline definition
*----------------------------------------------------------------------------
*/
/**
* Adapted for nxtmote.
* @author <NAME>
*/
#ifndef Board_h
#define Board_h
//#include "stdconst.h"
#include "AT91SAM7S256.h"
#define __inline static inline
#include "lib_AT91SAM7S256.h"
//#include "m_sched.h"
//#include "d_ioctrl.r"
#define __ramfunc
//#define AT91C_US_ASYNC_MODE ( AT91C_US_USMODE_NORMAL + AT91C_US_NBSTOP_1_BIT + AT91C_US_PAR_NONE + AT91C_US_CHRL_8_BITS + AT91C_US_CLKS_CLOCK )
#define AT91C_AIC_SRCTYPE_INT_HIGH_LEVEL ((unsigned int) 0x0 << 5) // (AIC) Internal Sources Code Label High-level Sensitive
#define true -1
#define false 0
#define HARDWAREInit {\
ULONG TmpReset;\
ULONG lkjh = 9;\
*AT91C_RSTC_RMR = 0xA5000401;\
*AT91C_AIC_DCR = 1;\
*AT91C_PITC_PIMR = (0x000FFFFF | 0x01000000);\
TmpReset = *AT91C_PITC_PIVR;\
TmpReset = TmpReset;/* Suppress warning*/\
*AT91C_PMC_PCER = (1L<<AT91C_ID_PIOA);\
}
/*-------------------------------*/
/* SAM7Board Memories Definition */
/*-------------------------------*/
// The AT91SAM7S64 embeds a 16-Kbyte SRAM bank, and 64 K-Byte Flash
#define INT_SARM 0x00200000
#define INT_SARM_REMAP 0x00000000
#define INT_FLASH 0x00000000
#define INT_FLASH_REMAP 0x01000000
#define FLASH_PAGE_NB 1024
#define FLASH_PAGE_LOCK 32
#define FLASH_PAGE_SIZE 256
/*-----------------*/
/* Leds Definition */
/*-----------------*/
/* PIO Flash PA PB PIN */
#define LED1 (1<<0) /* PA0 / PGMEN0 & PWM0 TIOA0 48 */
#define LED2 (1<<1) /* PA1 / PGMEN1 & PWM1 TIOB0 47 */
#define LED3 (1<<2) /* PA2 & PWM2 SCK0 44 */
#define LED4 (1<<3) /* PA3 & TWD NPCS3 43 */
#define NB_LEB 4
#define LED_MASK (LED1|LED2|LED3|LED4)
#endif /* Board_h */
|
tinyos-io/tinyos-3.x-contrib | uob/tossdr/ucla/gnuradio-802.15.4-demodulation/sos/modules/pong/pong.h | #ifndef _PING_H_
#define _PING_H_
#ifndef _MODULE_
int8_t ping_init();
#endif
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/simulator/omnienergypredictor.h | <filename>eon/eon/src/simulator/omnienergypredictor.h<gh_stars>1-10
/* This is the same predictor used in the HelioMote project
* It is a simple autoregressive filter of order 1.
*
*
*/
#ifndef OMNIENERGYPREDICTOR_H
#define OMNIENERGYPREDICTOR_H
#include "simulator.h"
#include "nodes.h"
using namespace std;
extern int64_t current_time;
int64_t start_energy;
int64_t min_time;
int64_t ep_last_prediction;
int64_t ep_cur_prediction;
int64_t ep_last_error;
int64_t ep_start_epoch;
int64_t ep_energy_counter;
void init_energy_predictor()
{
ep_start_epoch = 0;
ep_energy_counter = 0;
ep_cur_prediction = 0;
}
void ep_more_energy(int64_t energy, int64_t timestamp)
{
}
/*int64_t ep_get_power_level(string str){
string::size_type loc = str.find(":", 0);
if(loc != string::npos){
string power_time_string = str.substr(0, loc);
string energy_source_power_str = str.substr(loc+1);
int64_t energy_source_power = atoll(energy_source_power_str.c_str());
return energy_source_power;
}
return 0;
}*/
int64_t predict_energy(vector<event_t*> *timeline,
int64_t current_index,
int64_t hours)
{
int64_t result = 0;
int64_t index = current_index;
int64_t deadline;
int64_t ctime;
ctime = current_time;
deadline = current_time + (hours * 60 * 60 * 1000);
while (ctime < deadline)
{
if (index >= timeline->size())
{
break;
}
event_t* evt = timeline->at(index);
int event_type = evt->type;
if (event_type == UPDATE_BATTERY)
{
int64_t event_time = evt->time;
int64_t energyadd = evt->energy;
result += energyadd;
ctime = event_time;
}
index++;
}
return result;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | tinymulle/apps/MotionSensorTest/Motion.h | <reponame>tinyos-io/tinyos-3.x-contrib
#ifndef MOTION_H
#define MOTION_H
typedef nx_struct motion_msg {
nx_uint16_t data;
} motion_msg_t;
enum {
AM_MOTION_MSG = 8,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | hitdke/tos/sensorboards/synsb/sim/synsb.h | <reponame>tinyos-io/tinyos-3.x-contrib<gh_stars>0
// $Id: synsb.h,v 1.5 2010/06/25 14:03:30 pineapple_liu Exp $
/*
* Copyright (c) 2010 Data & Knowledge Engineering Research Center,
* Harbin Institute of Technology, P. R. China.
* All rights reserved.
*/
/**
* Demo sensor for synthetic sensorboard.
*
* @author <NAME> <<EMAIL>>
* @date Jun 18, 2010
*/
#ifndef __SYNSB_H__
#define __SYNSB_H__
#ifdef TOSSIM
#include <sim_synsb.h>
#else
#error "This sensorboard *synsb* only compiles in TOSSIM DB mode (aka. "sim", "sim-sf", etc.)."
#endif
#endif /* __SYN_SB_H__ */
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/telos/fluxstatedecider.h | <reponame>tinyos-io/tinyos-3.x-contrib
#ifndef FLUXSTATEDECIDER_H_INCLUDED
#define FLUXSTATEDECIDER_H_INCLUDED
#include "../nodes.h"
#include "fluxenergypredictor.h"
uint8_t decide_state (uint16_t connid, bool data)
{
uint8_t state = 0; //set to max state
uint8_t timeframe = 0;
int32_t netenergy;
int32_t battery;
while (timeframe < NUMTIMEFRAMES && state < STATE_BASE)
{
netenergy = predict_energy(timeframe, state);
battery = get_battery_reserve();
if (battery + netenergy <= 0)
{
state++;
} else {
timeframe++;
}
}
return state;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | intelmote2/support/sdk/c/camera_cmd/status.c | <reponame>tinyos-io/tinyos-3.x-contrib<gh_stars>1-10
/**
* This file is automatically generated by mig. DO NOT EDIT THIS FILE.
* This file implements the functions for encoding and decoding the
* 'status' message type. See status.h for more details.
*/
#include <message.h>
#include "status.h"
uint16_t status_node_id_get(tmsg_t *msg)
{
return tmsg_read_ube(msg, 0, 16);
}
void status_node_id_set(tmsg_t *msg, uint16_t value)
{
tmsg_write_ube(msg, 0, 16, value);
}
uint16_t status_seqNo_get(tmsg_t *msg)
{
return tmsg_read_ube(msg, 16, 16);
}
void status_seqNo_set(tmsg_t *msg, uint16_t value)
{
tmsg_write_ube(msg, 16, 16, value);
}
uint16_t status_parent_get(tmsg_t *msg)
{
return tmsg_read_ube(msg, 32, 16);
}
void status_parent_set(tmsg_t *msg, uint16_t value)
{
tmsg_write_ube(msg, 32, 16, value);
}
uint16_t status_ETX_get(tmsg_t *msg)
{
return tmsg_read_ube(msg, 48, 16);
}
void status_ETX_set(tmsg_t *msg, uint16_t value)
{
tmsg_write_ube(msg, 48, 16, value);
}
|
tinyos-io/tinyos-3.x-contrib | eon/apps/turtle_snapper/impl/mica2dot/typechecks.h | #ifndef TYPECHECKS_H_INCLUDED
#define TYPECHECKS_H_INCLUDED
/*
AM_BEGIN_TRAVERSAL_MSG = 17,
AM_GO_NEXT_MSG = 18,
AM_GET_NEXT_CHUNK = 19,
AM_GET_BUNDLE_MSG = 20,
AM_DELETE_BUNDLE_MSG = 21,
AM_END_DATA_COLLECTION_SESSION = 22,
AM_BUNDLE_INDEX_ACK = 23
*/
bool
IsGetNextChunkMsg (int value)
{
return value == AM_GET_NEXT_CHUNK;
}
bool
IsBeginTraversalMsg (int value)
{
return value == AM_BEGIN_TRAVERSAL_MSG;
}
bool
IsGoNextMsg (int value)
{
return value == AM_GO_NEXT_MSG;
}
bool
IsDeleteBundleMsg (int value)
{
return value == AM_DELETE_BUNDLE_MSG;
}
bool
IsDeleteAllBundlesMsg (int value)
{
return value == AM_DELETE_ALL_BUNDLES_MSG;
}
bool
IsStreamFull (uint32_t value)
{
return value > 1;
}
bool
IsEndCollectionSession (int value)
{
return value == AM_END_DATA_COLLECTION_SESSION;
}
bool
IsGetBundleMsg (int value)
{
return value == AM_GET_BUNDLE_MSG;
}
#endif // TYPECHECKS_H_INCLUDED
|
tinyos-io/tinyos-3.x-contrib | diku/mcs51/tos/chips/cc2430/timer/CC2430Timer.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.
*/
/**
*
* The 4 timers are controlled through 3 interfaces, that are very
* similar. Each type of timer has been given a seperate interface to
* avoid the misunderstanding that the timers are interchangeable - the
* timers differ substantially in bit width, prescaler (clock divider)
* values, timer modes, etc. even though there methods are very similar
* (get/set mode, prescaler, etc.).
*
* Timer 1 through 4 uses the system clock as source. This frequency
* the system clock is determined by the CLKCON.TICKSPD register, which
* then again is subdevided by the appropriate presc
*
* The sleep and watch dog timer uses the 32.768 kHz clock as source
* (either internal or external). Despites it's name the sleep timer
* can operate in all modes.
*
* The sleep and watch dog timers are not exported at this time.
*
*/
/**
*
* @author <NAME> <<EMAIL>>
*/
#ifndef _H_CC2430Timer_H
#define _H_CC2430Timer_H
/***********************************************************************
* CLKCON *
***********************************************************************/
/*
* Bit field constants
*/
enum {
CC2430_SLEEP_OSC32K_CALDIS = 7,
CC2430_SLEEP_XOSC_STB = 6,
CC2430_SLEEP_HFRC_STB = 5,
CC2430_SLEEP_DIV = 3, // first bit in 2-bit field
CC2430_SLEEP_OSC_PD = 2,
CC2430_SLEEP_MODE = 0, // first bit in 2-bit field
CC2430_SLEEP_MODE_MASK = 3
};
enum {
CC2430_SLEEP_POWERMODE_0 = 0,
CC2430_SLEEP_POWERMODE_1 = 1,
CC2430_SLEEP_POWERMODE_2 = 2,
CC2430_SLEEP_POWERMODE_3 = 3
};
enum {
CC2430_CLKCON_OSC32K = 7,
CC2430_CLKCON_OSC = 6,
CC2430_CLKCON_TICKSPD = 3, // first bit in 2-bit field
CC2430_CLKCON_CLKSPD = 0, // Will be set by MCU when OSC is selected
CC2430_CLKCON_TICKSPD_MASK = 0x38
};
/*
* CLKCON.TICKSPD values. The timers further subdevide this value
*/
enum cc2430_tick_spd_t {
CC2430_TICKF_DIV_1 = 0x0 << CC2430_CLKCON_TICKSPD,
CC2430_TICKF_DIV_2 = 0x1 << CC2430_CLKCON_TICKSPD,
CC2430_TICKF_DIV_4 = 0x2 << CC2430_CLKCON_TICKSPD,
CC2430_TICKF_DIV_8 = 0x3 << CC2430_CLKCON_TICKSPD,
CC2430_TICKF_DIV_16 = 0x4 << CC2430_CLKCON_TICKSPD,
CC2430_TICKF_DIV_32 = 0x5 << CC2430_CLKCON_TICKSPD,
CC2430_TICKF_DIV_64 = 0x6 << CC2430_CLKCON_TICKSPD,
CC2430_TICKF_DIV_128 = 0x7 << CC2430_CLKCON_TICKSPD
};
/***********************************************************************
* Timer 1 *
***********************************************************************/
/*
* T1CTL bit fields. See cc2430 datasheet p. 97
*/
enum {
CC2430_T1CTL_CH2IF = 0x7,
CC2430_T1CTL_CH1IF = 0x6,
CC2430_T1CTL_CH0IF = 0x5,
CC2430_T1CTL_OVFIF = 0x4,
CC2430_T1CTL_DIV = 0x2, // 2 bit field
CC2430_T1CTL_MODE = 0x0, // 2 bit field
CC2430_T1CTL_MODE_MASK = 0x3,
CC2430_T1CTL_DIV_MASK = 0xc,
CC2430_T1CTL_IF_MASK = 0xf0
};
/*
* Timer 1 modes. See cc2430 datasheet p. 97
*/
enum cc2430_timer1_mode_t {
CC2430_TIMER1_MODE_OFF = 0x0 << CC2430_T1CTL_MODE,
CC2430_TIMER1_MODE_FREE = 0x1 << CC2430_T1CTL_MODE,
CC2430_TIMER1_MODE_MODULO = 0x2 << CC2430_T1CTL_MODE,
CC2430_TIMER1_MODE_UPDOWN = 0x3 << CC2430_T1CTL_MODE
};
/*
* Timer 1 provides additional information on why an interrupt was
* generated in the register T1CTL. See cc2430 datasheep p. 104
*/
enum cc2430_timer1_if_t {
CC2430_T1_CH2IF = _BV(CC2430_T1CTL_CH2IF),
CC2430_T1_CH1IF = _BV(CC2430_T1CTL_CH1IF),
CC2430_T1_CH0IF = _BV(CC2430_T1CTL_CH0IF),
CC2430_T1_OVFIF = _BV(CC2430_T1CTL_OVFIF)
};
/*
* See cc2430 datasheet p. 104
*/
enum cc2430_timer1_prescaler_t {
CC2430_TIMER1_DIV_1 = 0x0 << CC2430_T1CTL_DIV,
CC2430_TIMER1_DIV_8 = 0x1 << CC2430_T1CTL_DIV,
CC2430_TIMER1_DIV_32 = 0x2 << CC2430_T1CTL_DIV,
CC2430_TIMER1_DIV_128 = 0x3 << CC2430_T1CTL_DIV
};
/*
* T1CCTLx bit locations
*/
enum {
CC2430_T1CCTLx_CPSEL = 0x7,
CC2430_T1CCTLx_IM = 0x6,
CC2430_T1CCTLx_CMP = 0x3,
CC2430_T1CCTLx_MODE = 0x2,
CC2430_T1CCTLx_CAP = 0x0
};
/***********************************************************************
* Timer 2 (MAC) *
***********************************************************************/
/*
* Timer MAC modes. See cc2430 datasheet p. 97
*/
enum cc2430_timerMAC_mode_t {
CC2430_TIMERMAC_MODE_IDLE = 0x0,
CC2430_TIMERMAC_MODE_RUN = 0x1
};
/*
* T2CNF bit fields
*/
enum cc2430_timerMAC_T2CNF_t {
CC2430_T2CNF_CMPIF = 0x7,
CC2430_T2CNF_PERIF = 0x6,
CC2430_T2CNF_OFCMPIF = 0x5,
CC2430_T2CNF_CMSEL = 0x3,
CC2430_T2CNF_SYNC = 0x1,
CC2430_T2CNF_RUN = 0x0
};
/*
* T2PEROF2 bit fields
*/
enum cc2430_timerMAC_T2PEROF2_t {
CC2430_T2PEROF2_CMPIM = 0x7,
CC2430_T2PEROF2_PERIM = 0x6,
CC2430_T2PEROF2_OFCMPIM = 0x5
};
enum cc2430_timerMAC_if_t {
CC2430_TMAC_CMPIF = _BV(CC2430_T2CNF_CMPIF),
CC2430_TMAC_PERIF = _BV(CC2430_T2CNF_PERIF),
CC2430_TMAC_OFCMPIF = _BV(CC2430_T2CNF_OFCMPIF)
};
enum cc2430_timerMAC_interval_t {
CC2430_TIMERWDT_32768 = 0,
CC2430_TIMERWDT_8192 = 1,
CC2430_TIMERWDT_512 = 2,
CC2430_TIMERWDT_64 = 3
};
/***********************************************************************
* Timer 3 and 4 *
***********************************************************************/
/*
* Timer 3 and 4 provide additional information on why an interrupt was
* generated in the register TIMIF. See cc2430 datasheep p. 124.
*
* These registers are also bitaddressable
*/
enum {
CC2430_TIMIF_OVFIM = 0x6
};
enum cc2430_timer34_if_t {
CC2430_TIMIF_T4CH1IF = 0x5, // Corresponds to sbit T4CH1IF
CC2430_TIMIF_T4CH0IF = 0x4, // Corresponds to sbit T4CH0IF
CC2430_TIMIF_T4OVFIF = 0x3, // Corresponds to sbit T4OVFIF
CC2430_TIMIF_T3CH1IF = 0x2, // Corresponds to sbit T3CH1IF
CC2430_TIMIF_T3CH0IF = 0x1, // Corresponds to sbit T3CH0IF
CC2430_TIMIF_T3OVFIF = 0x0 // Corresponds to sbit T3OVFIF
};
/*
* Timer 3 and 4 modes. See cc2430 datasheet p. 118
*/
enum cc2430_timer3_4_mode_t {
CC2430_TIMER3_4_MODE_FREE = 0x0,
CC2430_TIMER3_4_MODE_DOWN = 0x1,
CC2430_TIMER3_4_MODE_MODULO = 0x2,
CC2430_TIMER3_4_MODE_UPDOWN = 0x3
};
/*
* Bitmasks for T3CTL
*/
enum {
CC2430_T34CTL_DIV = 0x5, // 3 bit fild
CC2430_T34CTL_START = 0x4,
CC2430_T34CTL_OVFIM = 0x3,
CC2430_T34CTL_WDTIF = 0x3,
CC2430_T34CTL_CLR = 0x2,
CC2430_T34CTL_MODE = 0x0, // 2 bit fild
CC2430_T34CTL_MODE_MASK = 0x3,
CC2430_T34CTL_DIV_MASK = 0xe0
};
/*
* See cc2430 datasheet p. 118
*/
enum cc2430_timer3_4_prescaler_t {
CC2430_TIMER3_4_DIV_1 = 0x0 << CC2430_T34CTL_DIV,
CC2430_TIMER3_4_DIV_2 = 0x1 << CC2430_T34CTL_DIV,
CC2430_TIMER3_4_DIV_4 = 0x2 << CC2430_T34CTL_DIV,
CC2430_TIMER3_4_DIV_8 = 0x3 << CC2430_T34CTL_DIV,
CC2430_TIMER3_4_DIV_16 = 0x4 << CC2430_T34CTL_DIV,
CC2430_TIMER3_4_DIV_32 = 0x5 << CC2430_T34CTL_DIV,
CC2430_TIMER3_4_DIV_64 = 0x6 << CC2430_T34CTL_DIV,
CC2430_TIMER3_4_DIV_128 = 0x7 << CC2430_T34CTL_DIV
};
/***********************************************************************
* Timer WDT *
***********************************************************************/
/*
* Bit locations for WDCTL
*/
enum {
CC2430_WDCTL_CLR = 0x4,
CC2430_WDCTL_EN = 0x3,
CC2430_WDCTL_MODE = 0x2,
CC2430_WDCTL_INT = 0x0,
CC2430_WDCTL_INT_MASK = 0x3
};
enum cc2430_timerWDT_mode_t {
CC2430_TIMERWDT_MODE_WDT = 0x0 << CC2430_WDCTL_MODE,
CC2430_TIMERWDT_MODE_TIMER = 0x1 << CC2430_WDCTL_MODE
};
#endif //_H_CC2430Timer_H
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/usb.c | /*
* Main API entry point
*
* Copyright (c) 2000-2003 <NAME> <<EMAIL>>
*
* This library is covered by the LGPL, read LICENSE for details.
*/
#include <stdlib.h> /* getenv */
#include <stdio.h> /* stderr */
#include <string.h> /* strcmp */
#include <errno.h>
#include "usbi.h"
int usb_debug = 0;
struct usb_bus *_usb_busses = NULL;
int usb_find_busses(void)
{
struct usb_bus *busses, *bus;
int ret, changes = 0;
ret = usb_os_find_busses(&busses);
if (ret < 0)
return ret;
/*
* Now walk through all of the busses we know about and compare against
* this new list. Any duplicates will be removed from the new list.
* If we don't find it in the new list, the bus was removed. Any
* busses still in the new list, are new to us.
*/
bus = _usb_busses;
while (bus) {
int found = 0;
struct usb_bus *nbus, *tbus = bus->next;
nbus = busses;
while (nbus) {
struct usb_bus *tnbus = nbus->next;
if (!strcmp(bus->dirname, nbus->dirname)) {
/* Remove it from the new busses list */
LIST_DEL(busses, nbus);
usb_free_bus(nbus);
found = 1;
break;
}
nbus = tnbus;
}
if (!found) {
/* The bus was removed from the system */
LIST_DEL(_usb_busses, bus);
usb_free_bus(bus);
changes++;
}
bus = tbus;
}
/*
* Anything on the *busses list is new. So add them to usb_busses and
* process them like the new bus it is.
*/
bus = busses;
while (bus) {
struct usb_bus *tbus = bus->next;
/*
* Remove it from the temporary list first and add it to the real
* usb_busses list.
*/
LIST_DEL(busses, bus);
LIST_ADD(_usb_busses, bus);
changes++;
bus = tbus;
}
return changes;
}
int usb_find_devices(void)
{
struct usb_bus *bus;
int ret, changes = 0;
for (bus = usb_busses; bus; bus = bus->next) {
struct usb_device *devices, *dev;
/* Find all of the devices and put them into a temporary list */
ret = usb_os_find_devices(bus, &devices);
if (ret < 0)
return ret;
/*
* Now walk through all of the devices we know about and compare
* against this new list. Any duplicates will be removed from the new
* list. If we don't find it in the new list, the device was removed.
* Any devices still in the new list, are new to us.
*/
dev = bus->devices;
while (dev) {
int found = 0;
struct usb_device *ndev, *tdev = dev->next;
ndev = devices;
while (ndev) {
struct usb_device *tndev = ndev->next;
if (!strcmp(dev->filename, ndev->filename)) {
/* Remove it from the new devices list */
LIST_DEL(devices, ndev);
usb_free_dev(ndev);
found = 1;
break;
}
ndev = tndev;
}
if (!found) {
/* The device was removed from the system */
LIST_DEL(bus->devices, dev);
usb_free_dev(dev);
changes++;
}
dev = tdev;
}
/*
* Anything on the *devices list is new. So add them to bus->devices and
* process them like the new device it is.
*/
dev = devices;
while (dev) {
struct usb_device *tdev = dev->next;
/*
* Remove it from the temporary list first and add it to the real
* bus->devices list.
*/
LIST_DEL(devices, dev);
LIST_ADD(bus->devices, dev);
/*
* Some ports fetch the descriptors on scanning (like Linux) so we don't
* need to fetch them again.
*/
if (!dev->config) {
usb_dev_handle *udev;
udev = usb_open(dev);
if (udev) {
usb_fetch_and_parse_descriptors(udev);
usb_close(udev);
}
}
changes++;
dev = tdev;
}
usb_os_determine_children(bus);
}
return changes;
}
void usb_init(void)
{
if (getenv("USB_DEBUG"))
usb_set_debug(atoi(getenv("USB_DEBUG")));
usb_os_init();
}
usb_dev_handle *usb_open(struct usb_device *dev)
{
usb_dev_handle *udev;
udev = malloc(sizeof(*udev));
if (!udev)
return NULL;
udev->fd = -1;
udev->device = dev;
udev->bus = dev->bus;
udev->config = udev->interface = udev->altsetting = -1;
if (usb_os_open(udev) < 0) {
free(udev);
return NULL;
}
return udev;
}
int usb_get_string(usb_dev_handle *dev, int index, int langid, char *buf,
size_t buflen)
{
/*
* We can't use usb_get_descriptor() because it's lacking the index
* parameter. This will be fixed in libusb 1.0
*/
return usb_control_msg(dev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
(USB_DT_STRING << 8) + index, langid, buf, buflen, 1000);
}
int usb_get_string_simple(usb_dev_handle *dev, int index, char *buf, size_t buflen)
{
char tbuf[255]; /* Some devices choke on size > 255 */
int ret, langid, si, di;
/*
* Asking for the zero'th index is special - it returns a string
* descriptor that contains all the language IDs supported by the
* device. Typically there aren't many - often only one. The
* language IDs are 16 bit numbers, and they start at the third byte
* in the descriptor. See USB 2.0 specification, section 9.6.7, for
* more information on this. */
ret = usb_get_string(dev, 0, 0, tbuf, sizeof(tbuf));
if (ret < 0)
return ret;
if (ret < 4)
return -EIO;
langid = tbuf[2] | (tbuf[3] << 8);
ret = usb_get_string(dev, index, langid, tbuf, sizeof(tbuf));
if (ret < 0)
return ret;
if (tbuf[1] != USB_DT_STRING)
return -EIO;
if (tbuf[0] > ret)
return -EFBIG;
for (di = 0, si = 2; si < tbuf[0]; si += 2) {
if (di >= ((int)buflen - 1))
break;
if (tbuf[si + 1]) /* high byte */
buf[di++] = '?';
else
buf[di++] = tbuf[si];
}
buf[di] = 0;
return di;
}
int usb_close(usb_dev_handle *dev)
{
int ret;
ret = usb_os_close(dev);
free(dev);
return ret;
}
struct usb_device *usb_device(usb_dev_handle *dev)
{
return dev->device;
}
void usb_free_dev(struct usb_device *dev)
{
usb_destroy_configuration(dev);
free(dev->children);
free(dev);
}
struct usb_bus *usb_get_busses(void)
{
return _usb_busses;
}
void usb_free_bus(struct usb_bus *bus)
{
free(bus);
}
|
tinyos-io/tinyos-3.x-contrib | ucd/Octopus/motes/OctopusConfig.h | <filename>ucd/Octopus/motes/OctopusConfig.h
// $Id: OctopusConfig.h,v 1.4 2008/03/13 14:16:37 a_barbirato Exp $
/* tab:4
* Copyright (c) 2007 University College Dublin.
* 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 and the following
* two paragraphs appear in all copies of this software.
*
* IN NO EVENT SHALL UNIVERSITY COLLEGE DUBLIN 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
* UNIVERSITY COLLEGE DUBLIN HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* UNIVERSITY COLLEGE DUBLIN 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 UNIVERSITY COLLEGE DUBLIN HAS NO
* OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
* MODIFICATIONS.
*
* Authors: <NAME>, <NAME>, and <NAME>
* Date created: 2007/09/07
*
*/
/**
* @author <NAME>, <NAME>, and <NAME>
*/
#ifndef OCTOPUS_CONFIG_H
#define OCTOPUS_CONFIG_H
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* This file includes every constant that can be defined by *
* a final user. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
Choice of the protocol used to repatriate data to the root
of the network.
Two protocols can't have the same name, even if they are
not of the same type
*/
#define LOW_POWER_LISTENING
#define COLLECTION_PROTOCOL // cf TEP 119: Collection.
//#define DUMMY_COLLECT_PROTOCOL // not working
/*
Choice of the protocol used to broadcast data over the network
*/
#define DISSEMINATION_PROTOCOL // cf TEP 118: Dissemination.
//#define DUMMY_BROADCAST_PROTOCOL // not working
/*
S E N S O R
Sampling of the sensor. The unit is the milliseconds.
MINIMUM_SAMPLING_PERIOD is the minimum value that should
be broadcasted to the network to avoid congestion issues.
A formula that can be used is, with N the number of motes
of the network, and MINIMUM_SAMPLING_PERIOD in ms :
MINIMUM_SAMPLING_PERIOD = 100 * N
Threshold of the sensor. A threshold of 0 means that
the value is sent every time. Else the threshold is
a 16-bits unsigned integer.
M O D E
The user can choose either the automatic aka timer-driven
mode (MODE_AUTO) or the manual aka request-driven mode
(MODE_QUERY).
S L E E P & A W A K E D U T Y C Y C L E
The user can define the sleep duty cycle and the awake
duty cycle in units of [percent * 100]. For example, to
get a 0.05% duty cycle, use the value 5, and for a 100%
duty cycle (always on), use the value 10000.
This is the equivalent of setting the local sleep
interval explicitly.
*/
enum {
DEFAULT_SAMPLING_PERIOD = 1024,
MINIMUM_SAMPLING_PERIOD = 1024,
DEFAULT_THRESHOLD = 0,
DEFAULT_MODE = MODE_AUTO,
DEFAULT_SLEEP_DUTY_CYCLE = 2000, // 20%
DEFAULT_AWAKE_DUTY_CYCLE = 9000 // 90%
};
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/apps/turtle_snapper/impl/tinynode/uservariables.h | #ifndef USERVARIABLES_H_
#define USERVARIABLES_H_
#define NUM_TURTLES 20
/**************************************************************************************************
// GLOBAL SINGLE STREAM VARIABLES
**************************************************************************************************/
// should always be accessed atomically;
enum
{
LBFLOW_RECEIVING = 0,
LBFLOW_IDLE = 1
};
//uint8_t listen_beacon_flow_state;
uint16_t g_addr;
//this should indicate whether or not we are in a connection event.
//bool g_connected = FALSE;
bool g_active = TRUE;
//bool g_missed_last_reading = FALSE;
bool g_in_gps = FALSE;
uint16_t g_lastAddr = 0xFFFF; //default to broadcast
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/linuxsim/rt_structs.h | #ifndef RT_STRUCTS_H_INCLUDED
#define RT_STRUCTS_H_INCLUDED
#include <stdint.h>
typedef int8_t result_t;
#define TRUE 1
#define FALSE 0
typedef struct rt_data
{
uint16_t sessionID;
//uint32_t starttime;
uint16_t weight;
//uint8_t minstate;
//uint32_t elapsed_us;
} rt_data;
typedef struct GenericNode
{
rt_data _pdata;
} GenericNode;
#endif
|
tinyos-io/tinyos-3.x-contrib | diku/mcs51/tos/platforms/nRF24E1_EVBOARD/platform.h | <reponame>tinyos-io/tinyos-3.x-contrib
//Nothing to see here. move along
|
tinyos-io/tinyos-3.x-contrib | kasetsart/tos/chips/atm328/atm328hardware.h | <gh_stars>1-10
/**
* This file defines various macros and functions for ATmega328 low-level
* hardware control such as interrupts and power management.
*
* @notes
* This file is modified from
* <code>tinyos-2.1.0/tos/chips/atm128/atm128hardware.h</code>
*
* @author
* <NAME> (<EMAIL>)
*/
#ifndef _H_atmega328hardware_H
#define _H_atmega328hardware_H
#include <avr/io.h>
#if __AVR_LIBC_VERSION__ >= 10400UL
#include <avr/interrupt.h>
#else
#include <avr/interrupt.h>
#include <avr/signal.h>
#endif
#include <avr/wdt.h>
#include <avr/pgmspace.h>
#include "atm328const.h"
/* We need slightly different defs than SIGNAL, INTERRUPT */
#define AVR_ATOMIC_HANDLER(signame) \
ISR(signame) @atomic_hwevent() @C()
#define AVR_NONATOMIC_HANDLER(signame) \
void signame(void) __attribute__ ((interrupt)) @hwevent() @C()
/* Macro to create union casting functions. */
#define DEFINE_UNION_CAST(func_name, from_type, to_type) \
to_type func_name(from_type x) { \
union {from_type f; to_type t;} c = {f:x}; return c.t; }
// Bit operators using bit number
#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))
/* Enables interrupts. */
inline void __nesc_enable_interrupt() @safe() {
sei();
}
/* Disables all interrupts. */
inline void __nesc_disable_interrupt() @safe() {
cli();
}
/* Defines data type for storing interrupt mask state during atomic. */
typedef uint8_t __nesc_atomic_t;
__nesc_atomic_t __nesc_atomic_start(void);
void __nesc_atomic_end(__nesc_atomic_t original_SREG);
#ifndef NESC_BUILD_BINARY
/* @spontaneous() functions should not be included when NESC_BUILD_BINARY
is #defined, to avoid duplicate functions definitions wheb binary
components are used. Such functions do need a prototype in all cases,
though. */
/* Saves current interrupt mask state and disables interrupts. */
inline __nesc_atomic_t
__nesc_atomic_start(void) @spontaneous() @safe()
{
__nesc_atomic_t result = SREG;
__nesc_disable_interrupt();
asm volatile("" : : : "memory"); /* ensure atomic section effect visibility */
return result;
}
/* Restores interrupt mask to original state. */
inline void
__nesc_atomic_end(__nesc_atomic_t original_SREG) @spontaneous() @safe()
{
asm volatile("" : : : "memory"); /* ensure atomic section effect visibility */
SREG = original_SREG;
}
#endif
/* Defines the mcu_power_t type for atm328 power management. */
typedef uint8_t mcu_power_t @combine("mcombine");
enum {
ATM328_POWER_IDLE = 0,
ATM328_POWER_ADC_NR = 1,
ATM328_POWER_EXT_STANDBY = 2,
ATM328_POWER_SAVE = 3,
ATM328_POWER_STANDBY = 4,
ATM328_POWER_DOWN = 5,
};
/* Combine function. */
mcu_power_t mcombine(mcu_power_t m1, mcu_power_t m2) @safe() {
return (m1 < m2)? m1: m2;
}
#endif //_H_atmega328hardware_H
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/driver/driver_api.h | /* 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
*/
#ifndef __DRIVER_API_H__
#define __DRIVER_API_H__
enum {
LIBUSB_DEBUG_OFF,
LIBUSB_DEBUG_ERR,
LIBUSB_DEBUG_MSG,
};
/* 64k */
#define LIBUSB_MAX_READ_WRITE 0x10000
#define LIBUSB_MAX_NUMBER_OF_DEVICES 256
#define LIBUSB_MAX_NUMBER_OF_CHILDREN 32
#define LIBUSB_IOCTL_SET_CONFIGURATION CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x801, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_GET_CONFIGURATION CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x802, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_SET_INTERFACE CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x803, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_GET_INTERFACE CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x804, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_SET_FEATURE CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x805, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_CLEAR_FEATURE CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x806, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_GET_STATUS CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x807, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_SET_DESCRIPTOR CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x808, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_GET_DESCRIPTOR CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x809, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_INTERRUPT_OR_BULK_WRITE CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x80A, METHOD_IN_DIRECT, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_INTERRUPT_OR_BULK_READ CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x80B, METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_VENDOR_WRITE CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x80C, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_VENDOR_READ CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x80D, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_RESET_ENDPOINT CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x80E, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_ABORT_ENDPOINT CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x80F, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_RESET_DEVICE CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x810, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_SET_DEBUG_LEVEL CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x811, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_GET_VERSION CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x812, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_ISOCHRONOUS_WRITE CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x813, METHOD_IN_DIRECT, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_ISOCHRONOUS_READ CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x814, METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_CLAIM_INTERFACE CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x815, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define LIBUSB_IOCTL_RELEASE_INTERFACE CTL_CODE(FILE_DEVICE_UNKNOWN,\
0x816, METHOD_BUFFERED, FILE_ANY_ACCESS)
#include <pshpack1.h>
typedef struct {
unsigned int timeout;
union {
struct
{
unsigned int configuration;
} configuration;
struct
{
unsigned int interface;
unsigned int altsetting;
} interface;
struct
{
unsigned int endpoint;
unsigned int packet_size;
} endpoint;
struct
{
unsigned int type;
unsigned int recipient;
unsigned int request;
unsigned int value;
unsigned int index;
} vendor;
struct
{
unsigned int recipient;
unsigned int feature;
unsigned int index;
} feature;
struct
{
unsigned int recipient;
unsigned int index;
unsigned int status;
} status;
struct
{
unsigned int type;
unsigned int index;
unsigned int language_id;
unsigned int recipient;
} descriptor;
struct
{
unsigned int level;
} debug;
struct
{
unsigned int major;
unsigned int minor;
unsigned int micro;
unsigned int nano;
} version;
};
} libusb_request;
#include <poppack.h>
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/quanto/tools/quanto/compression/quanto_decode.c | <filename>berkeley/quanto/tools/quanto/compression/quanto_decode.c
/*
* Copyright (c) 2009 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Author: <NAME> <<EMAIL>>
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define _QUANTO_C
#include "libquantocode.h"
// Includes from the Quanto code:
#include "RawUartMsg.h"
// defines entry_t
#include "QuantoLogCompressedMyUartWriter.h"
// defines CBLOCKSIZE, BUFFERSIZE, BITBUFFERSIZE
/* Decodes a stream of quanto log entries encoded by
* the QuantoLogCompressedMyUartWriter.
* The program reads from STDIN the output of Listen, and
* assumes the format: <block size> <bit stream>
* The compression uses a combination of techniques.
* For discrete entities (type, resource, activity), we
* use an 8-bit Move To Front encoder followed by an Elias-gamma
* encoder. For continuous entities (time and icount), we
* use a simple delta encoder followed by Elias-gamma encoding
* as well. Since EG can't encode 0, we add 1 to some of these.
* The decoding process is the reverse transformations.
*/
/* This function reverses what the encoder does. It must match
* what QuantoLogCompressedMyUartWriterP.CompressTask does.
*/
int
decode_block (bitBuf* buf, entry_t* block, int block_size, bool sync)
{
int i;
uint32_t d;
uint8_t m;
static mtf_encoder mtf;
static uint32_t last_time = 0;
static uint32_t last_icount = 0;
if (sync) {
mtf_init(&mtf);
}
//decode type (EG(MTF+1))'
//mtf_init(&mtf);
for (i = 0; i < block_size; i++) {
fprintf(stderr,"type, i: %d ", i);
if (! (d = elias_gamma_decode(buf)))
break;
d -= 1;
m = mtf_decode(&mtf, (uint8_t)d);
block[i].type = m;
}
if (i < block_size) return 0;
//decode resource (EG(MTF+1))'
//mtf_init(&mtf);
for (i = 0; i < block_size; i++) {
fprintf(stderr,"res_id, i: %d ", i);
if (!(d = elias_gamma_decode(buf)))
break;
d -= 1;
m = mtf_decode(&mtf, (uint8_t)d);
block[i].res_id = m;
}
if (i < block_size) return 0;
//decode time (EG(delta))'
for (i = 0; i < block_size; i++) {
fprintf(stderr,"time, i: %d ", i);
if (!(d = elias_gamma_decode(buf)))
break;
if (i == 0 && sync) {
//decode absolute time+1
d -= 1;
} else {
//decode delta
d += last_time;
}
block[i].time = d;
last_time = d;
}
if (i < block_size) return 0;
//decode icount (EG(delta +1))'
for (i = 0; i < block_size; i++) {
fprintf(stderr,"icount, i: %d ", i);
if (!(d = elias_gamma_decode(buf)))
break;
if (i == 0 && sync) {
//decode absolute icount+1
d -= 1;
} else {
//decode delta
d += last_icount;
d -= 1;
}
block[i].ic = d;
last_icount = d;
}
if (i < block_size) return 0;
//decode activity MSB (EG(MTF+1))'
//mtf_init(&mtf);
for (i = 0; i < block_size; i++) {
fprintf(stderr,"act msb, i: %d ", i);
if (!(d = elias_gamma_decode(buf)))
break;
d -= 1;
m = mtf_decode(&mtf, (uint8_t)d);
block[i].act = ((uint16_t)m << 8);
}
if (i < block_size) return 0;
//decode activity LSB (EG(MTF+1))'
//mtf_init(&mtf);
for (i = 0; i < block_size; i++) {
fprintf(stderr,"act lsb, i: %d ", i);
if (!(d = elias_gamma_decode(buf)))
break;
d -= 1;
m = mtf_decode(&mtf, (uint8_t)d);
block[i].act |= (uint16_t)m & 0xff;
}
if (i < block_size) return 0;
return 1;
}
/* Prints the block of entries emulating the output of the regular logger,
* a sequence of bytes printed in capital hex representation, one entry
* per line. For integers larger than 1 byte we use big-endian, network order,
* most signigicant byte first. */
void print_block_hex(FILE* f, entry_t* block, int block_size)
{
int i;
for (i = 0; i < block_size; i++) {
fprintf(f, "%02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X\n",
block[i].type,
block[i].res_id,
(uint8_t)(block[i].time >> 24 & 0xff),
(uint8_t)(block[i].time >> 16 & 0xff),
(uint8_t)(block[i].time >> 8 & 0xff),
(uint8_t)(block[i].time & 0xff),
(uint8_t)(block[i].ic >> 24 & 0xff),
(uint8_t)(block[i].ic >> 16 & 0xff),
(uint8_t)(block[i].ic >> 8 & 0xff),
(uint8_t)(block[i].ic & 0xff),
(uint8_t)(block[i].act >> 8 & 0xff),
(uint8_t)(block[i].act & 0xff)
);
}
}
int main()
{
bitBuf *buf; //input from mote
entry_t *block = 0; //decoded log entries
char line_buf[BITBUFSIZE*3];
char* p;
int line_count = 0;
int error_lines = 0;
int initial_skip = 0;
int skipped_lines = 0;
int total_bytes = 0;
int decoded_bytes = 0;
int error_sync = 0;
int error_nosync = 0;
int error_skip_sync = 0;
int error_skip_nosync = 0;
int sync_lines = 0;
int nosync_lines = 0;
int header;
bool sync;
bool syncd = 0;
bool initial_sync = 0;
int block_size = 0;
unsigned int s;
uint8_t b;
buf = bitBuf_new(BITBUFSIZE);
memset(line_buf, 0, sizeof(line_buf));
while (fgets(line_buf, sizeof(line_buf), stdin) != NULL) {
line_count++;
fprintf(stderr, "line %d: %s", line_count, line_buf);
p = line_buf;
bitBuf_clear(buf);
//fill BitBuffer
while ( sscanf(p, "%X", &s) == 1) {
b = (uint8_t)s;
p += 3;
bitBuf_putByte(buf, b);
fprintf(stderr, "%02X ", b);
}
fprintf(stderr, "\n");
fprintf(stderr, "read %d bytes\n", bitBuf_length(buf));
// Guess the block size
if (block_size == 0) {
int count = 0;
fprintf(stderr, "guessing block size...");
for (count = 0; elias_gamma_decode(buf) != 0; count++);
if (count % 6 != 1) {
fprintf(stderr, " read %d integers, not 6b+1, confused.\n", count);
exit(1);
} else {
block_size = count / 6;
fprintf(stderr, " cool, block size is %d!\n", block_size);
}
//pretend it never happened
bitBuf_resetReadPos(buf);
//alocate block
block = (entry_t*)malloc(block_size*sizeof(entry_t));
}
//decode header
header = elias_gamma_decode(buf);
if (header == 1) {
sync = 0;
} else if (header == 2) {
sync = 1;
initial_sync |= sync;
} else {
fprintf(stderr, "This can't happen, header is not 1 or 2 (it is %d)\n", header);
exit(2);
}
syncd |= sync;
if (sync) {
sync_lines++;
} else {
nosync_lines++;
}
if (!syncd) {
fprintf(stderr, "waiting for MTF sync...\n");
if (!decode_block(buf, block, block_size, sync)) {
if (sync) {
error_skip_sync++;
} else {
error_skip_nosync++;
}
}
if (!initial_sync) {
initial_skip++;
} else {
skipped_lines++;
}
continue;
}
//we are syncd!
//decode block
if (!decode_block(buf, block, block_size, sync)) {
fprintf(stderr, "Error decoding line %d !!!\n", line_count);
error_lines++;
if (sync) {
error_sync++;
} else {
error_nosync++;
}
syncd = 0;
} else {
total_bytes += bitBuf_length(buf);
print_block_hex(stdout, block, block_size);
}
//just to make sure...
memset(line_buf, 0, sizeof(line_buf));
}
free(block);
//print some stats
decoded_bytes = 12 * block_size * (line_count - (skipped_lines + initial_skip + error_lines));
fprintf(stderr, "Total lines: %d ( %d initial skip, %d errors, %d skipped ). \nBlock size: %d Compr. Bytes: %d Decoded Bytes: %d Compression Factor: %f\n",
line_count, initial_skip, error_lines, skipped_lines,
block_size, total_bytes, decoded_bytes, 1.0*decoded_bytes/total_bytes);
fprintf(stderr, "Errors in sync lines: %d / %d (%.3f)\n",
error_sync + error_skip_sync, sync_lines,
(error_sync + error_skip_sync)*1.0/sync_lines);
fprintf(stderr, "Errors in nosync lines: %d / %d (%.3f)\n",
error_nosync + error_skip_nosync, nosync_lines,
(error_nosync + error_skip_nosync)*1.0/nosync_lines);
exit(0);
}
|
tinyos-io/tinyos-3.x-contrib | uob/tossdr/tos/lib/tossdr/sim_log.c | <filename>uob/tossdr/tos/lib/tossdr/sim_log.c
// $Id: sim_log.c,v 1.3 2010/03/26 15:17:01 mab-cn Exp $
/*
* "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 TOSSIM logging system.
*
* @author <NAME>
* @date November 9 2005
*/
#include <sim_log.h>
#include <stdio.h>
#include <stdarg.h>
#include <hashtable.h>
#include <string.h>
enum {
DEFAULT_CHANNEL_SIZE = 8
};
typedef struct sim_log_output {
int num;
FILE** files;
} sim_log_output_t;
typedef struct sim_log_channel {
const char* name;
int numOutputs;
int size;
FILE** outputs;
} sim_log_channel_t;
enum {
SIM_LOG_OUTPUT_COUNT = uniqueCount("TOSSIM.debug")
};
sim_log_output_t outputs[SIM_LOG_OUTPUT_COUNT];
struct hashtable* channelTable = NULL;
static unsigned int sim_log_hash(void* key);
static int sim_log_eq(void* key1, void* key2);
// First we count how many outputs there are,
// then allocate a FILE** large enough and fill it in.
// This FILE** might be larger than needed, because
// the outputs of the channels might have redundancies.
// E.g., if two channels A and B are both to stdout, then
// you don't want a channel of "A,B" to be doubly printed
// to stdout. So when the channel's FILE*s are copied
// into the debug point output array, this checks
// for redundancies by checking file descriptors.
static void fillInOutput(int id, char* name) {
char* termination = name;
char* namePos = name;
int count = 0;
char* newName = (char*)malloc(strlen(name) + 1);
memset(newName, 0, strlen(name) + 1);
// Count the outputs
while (termination != NULL) {
sim_log_channel_t* channel;
termination = strrchr(namePos, ',');
// If we've reached the end, just copy to the end
if (termination == NULL) {
strcpy(newName, namePos);
}
// Otherwise, memcpy over and null terminate
else {
memcpy(newName, namePos, (termination - namePos));
newName[termination - namePos] = 0;
}
channel = hashtable_search(channelTable, namePos);
if (channel != NULL) {
count += channel->numOutputs;
}
namePos = termination + 1;
}
termination = name;
namePos = name;
// Allocate
outputs[id].files = (FILE**)malloc(sizeof(FILE*) * count);
outputs[id].num = 0;
// Fill it in
while (termination != NULL) {
sim_log_channel_t* channel;
termination = strrchr(namePos, ',');
// If we've reached the end, just copy to the end
if (termination == NULL) {
strcpy(newName, namePos);
}
// Otherwise, memcpy over and null terminate
else {
memcpy(newName, namePos, (termination - namePos));
newName[termination - namePos] = 0;
}
channel = hashtable_search(channelTable, namePos);
if (channel != NULL) {
int i, j;
for (i = 0; i < channel->numOutputs; i++) {
int duplicate = 0;
int outputCount = outputs[id].num;
// Check if we already have this file descriptor in the output
// set, and if so, ignore it.
for (j = 0; j < outputCount; j++) {
if (fileno(outputs[id].files[j]) == fileno(channel->outputs[i])) {
duplicate = 1;
j = outputCount;
}
}
if (!duplicate) {
outputs[id].files[outputCount] = channel->outputs[i];
outputs[id].num++;
}
}
}
namePos = termination + 1;
}
}
void sim_log_init() {
int i;
channelTable = create_hashtable(128, sim_log_hash, sim_log_eq);
for (i = 0; i < SIM_LOG_OUTPUT_COUNT; i++) {
outputs[i].num = 1;
outputs[i].files = (FILE**)malloc(sizeof(FILE*));
outputs[i].files[0] = fdopen(1, "w"); // STDOUT
}
}
void sim_log_add_channel(char* name, FILE* file) {
sim_log_channel_t* channel;
channel = (sim_log_channel_t*)hashtable_search(channelTable, name);
// If there's no current entry, allocate one, initialize it,
// and insert it.
if (channel == NULL) {
char* newName = (char*)malloc(strlen(name) + 1);
strcpy(newName, name);
newName[strlen(name)] = 0;
channel = (sim_log_channel_t*)malloc(sizeof(sim_log_channel_t));
channel->name = newName;
channel->numOutputs = 0;
channel->size = DEFAULT_CHANNEL_SIZE;
channel->outputs = (FILE**)malloc(sizeof(FILE*) * channel->size);
memset(channel->outputs, 0, sizeof(FILE*) * channel->size);
hashtable_insert(channelTable, newName, channel);
}
// If the channel output table is full, double the size of
// channel->outputs.
if (channel->numOutputs == channel->size) {
FILE** newOutputs;
int newSize = channel->size * 2;
newOutputs = (FILE**)malloc(sizeof(FILE*) * newSize);
memcpy(newOutputs, channel->outputs, channel->size * sizeof(FILE**));
free(channel->outputs);
channel->outputs = newOutputs;
channel->size = newSize;
}
channel->outputs[channel->numOutputs] = file;
channel->numOutputs++;
sim_log_commit_change();
}
bool sim_log_remove_channel(char* output, FILE* file) {
sim_log_channel_t* channel;
int i;
channel = (sim_log_channel_t*)hashtable_search(channelTable, output);
if (channel == NULL) {
return FALSE;
}
// Note: if a FILE* has duplicates, this removes all of them
for (i = 0; i < channel->numOutputs; i++) {
FILE* f = channel->outputs[i];
if (file == f) {
memcpy(&channel->outputs[i], &channel->outputs[i + 1], (channel->numOutputs) - (i + 1));
channel->outputs[channel->numOutputs - 1] = NULL;
channel->numOutputs--;
}
}
return TRUE;
}
void sim_log_commit_change() {
int i;
for (i = 0; i < SIM_LOG_OUTPUT_COUNT; i++) {
if (outputs[i].files != NULL) {
outputs[i].num = 0;
free(outputs[i].files);
outputs[i].files = NULL;
}
}
}
void sim_log_debug(uint16_t id, char* string, const char* format, ...) {
va_list args;
int i;
if (outputs[id].files == NULL) {
fillInOutput(id, string);
}
for (i = 0; i < outputs[id].num; i++) {
FILE* file = outputs[id].files[i];
va_start(args, format);
fprintf(file, "DEBUG (%i): ", (int)sim_node());
vfprintf(file, format, args);
fflush(file);
}
}
void sim_log_error(uint16_t id, char* string, const char* format, ...) {
va_list args;
int i;
if (outputs[id].files == NULL) {
fillInOutput(id, string);
}
for (i = 0; i < outputs[id].num; i++) {
FILE* file = outputs[id].files[i];
va_start(args, format);
fprintf(file, "ERROR (%i): ", (int)sim_node());
vfprintf(file, format, args);
fflush(file);
}
}
void sim_log_debug_clear(uint16_t id, char* string, const char* format, ...) {
va_list args;
int i;
if (outputs[id].files == NULL) {
fillInOutput(id, string);
}
for (i = 0; i < outputs[id].num; i++) {
FILE* file = outputs[id].files[i];
va_start(args, format);
vfprintf(file, format, args);
fflush(file);
}
}
void sim_log_error_clear(uint16_t id, char* string, const char* format, ...) {
va_list args;
int i;
if (outputs[id].files == NULL) {
fillInOutput(id, string);
}
for (i = 0; i < outputs[id].num; i++) {
FILE* file = outputs[id].files[i];
va_start(args, format);
vfprintf(file, format, args);
fflush(file);
}
}
/* This is the sdbm algorithm, taken from
http://www.cs.yorku.ca/~oz/hash.html -pal */
static unsigned int sim_log_hash(void* key) {
char* str = (char*)key;
unsigned int hashVal = 0;
int hashChar;
while ((hashChar = *str++))
hashVal = hashChar + (hashVal << 6) + (hashVal << 16) - hashVal;
return hashVal;
}
static int sim_log_eq(void* key1, void* key2) {
return strcmp((char*)key1, (char*)key2) == 0;
}
|
tinyos-io/tinyos-3.x-contrib | uob/tossdr/tos/lib/tossdr/sim_log.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 TOSSIM logging system. Unlike in TinyOS 1.x, this logging
* system supports an arbitrary number of channels, denoted by
* a string identifier. A channel can be connected to any number
* of outputs, and a debug statement can be associated with any
* number of channels.
*
* @author <NAME>
* @date Nov 22 2005
*/
// $Id: sim_log.h,v 1.3 2010/03/26 15:17:01 mab-cn Exp $
#ifndef SIM_LOG_H_INCLUDED
#define SIM_LOG_H_INCLUDED
#ifndef TOSSIM_NO_DEBUG
#define dbg(s, ...) sim_log_debug(unique("TOSSIM.debug"), s, __VA_ARGS__)
#define dbg_clear(s, ...) sim_log_debug_clear(unique("TOSSIM.debug"), s, __VA_ARGS__)
#define dbgerror(s, ...) sim_log_error(unique("TOSSIM.debug"), s, __VA_ARGS__)
#define dbgerror_clear(s, ...) sim_log_error_clear(unique("TOSSIM.debug"), s, __VA_ARGS__)
#else
#define dbg(s, ...)
#define dbg_clear(s, ...)
#define dbgerror(s, ...)
#define dbgerror_clear(s, ...)
#endif
#ifdef __cplusplus
extern "C" {
#endif
void sim_log_init();
void sim_log_add_channel(char* output, FILE* file);
bool sim_log_remove_channel(char* output, FILE* file);
void sim_log_commit_change();
void sim_log_debug(uint16_t id, char* string, const char* format, ...);
void sim_log_error(uint16_t id, char* string, const char* format, ...);
void sim_log_debug_clear(uint16_t id, char* string, const char* format, ...);
void sim_log_error_clear(uint16_t id, char* string, const char* format, ...);
#ifdef __cplusplus
}
#endif
#endif // SIM_LOG_H_INCLUDED
|
tinyos-io/tinyos-3.x-contrib | uob/tossdr/tos/chips/atm128/sdr/atm128const.h | <filename>uob/tossdr/tos/chips/atm128/sdr/atm128const.h
/* $Id: atm128const.h,v 1.2 2009/05/28 21:13:06 mab-cn Exp $
* Copyright (c) 2005 Intel Corporation
* All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE
* file. If you do not find these files, copies can be found by writing to
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
* 94704. Attention: Intel License Inquiry.
*/
/*
* const_[u]int[8/16/32]_t types are used to declare single and array
* constants that should live in ROM/FLASH. These constants must be read
* via the corresponding read_[u]int[8/16/32]_t functions.
*
* This file defines the ATmega128 version of these types and functions.
* @author <NAME>
*/
#ifndef ATMEGA128CONST_H
#define ATMEGA128CONST_H
typedef uint8_t const_uint8_t PROGMEM;
typedef uint16_t const_uint16_t PROGMEM;
typedef uint32_t const_uint32_t PROGMEM;
typedef int8_t const_int8_t PROGMEM;
typedef int16_t const_int16_t PROGMEM;
typedef int32_t const_int32_t PROGMEM;
#define read_uint8_t(x) pgm_read_byte(x)
#define read_uint16_t(x) pgm_read_word(x)
#define read_uint32_t(x) pgm_read_dword(x)
#define read_int8_t(x) ((int8_t)pgm_read_byte(x))
#define read_int16_t(x) ((int16_t)pgm_read_word(x))
#define read_int32_t(x) ((int32_t)pgm_read_dword(x))
#endif
|
tinyos-io/tinyos-3.x-contrib | antlab-polimi/dpcm_C/jpegUncompress.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 <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "tinyos_macros.h"
#include "jpeghdr.h"
#include "ycc2rgb.h"
#include "idctfstBlk.h"
#include "quanttables_odrb.h"
#include "huffmanUncompress.h"
#include "decodeZeros.h"
//#define RLE_ONLY
void decode(code_header_t *header, unsigned char *dataIn, int8_t* decoded)
{
unsigned char dataTmp[header->sizeRLE];
uint32_t max_size = header->width*header->height;
uint32_t dc_size = max_size/64;
#ifdef RLE_ONLY
decodeDC(dataIn, decoded, dc_size);
decodeZeros(&dataIn[dc_size], &decoded[dc_size], header->sizeRLE, max_size-dc_size);
#else
FILE* fd;
uint32_t r=0;
uint32_t idx=header->sizeHUF;
Huffman_Uncompress(dataIn, dataTmp, header->sizeHUF, header->sizeRLE);
decodeDC(dataTmp, decoded, dc_size);
idx=decodeZeros(&dataTmp[dc_size], &decoded[dc_size], header->sizeRLE, max_size-dc_size);
#endif
return;
}
void decodeBytes(unsigned char *dataBuffer, int8_t* decoded, code_header_t *header)
//void decodeBytes(unsigned char *dataBuffer, int16_t* decoded, code_header_t *header)
{
memcpy(header,dataBuffer,CODE_HEADER_SIZE);
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=&dataBuffer[CODE_HEADER_SIZE];
decode(header, dataIn, decoded);
}
int32_t minim(int32_t x, int32_t y)
{
if (x<y)
return x;
return y;
}
void decodeFile(char *filename, int8_t* decoded, code_header_t *header, uint8_t idx)
//void decodeFile(char *filename, int16_t* decoded, code_header_t *header, uint8_t idx)
{
FILE *fdIn;
if (!(fdIn = fopen(filename, "r")) ){
printf("decodeFile: Can't open %s file for reading\n", filename);
return;
}
unsigned char line[1024];
int i=0,count, dataSize=0;
unsigned char *dataIn=0;
for (i=0; i<idx; i++)
{
count=fread(line,1,CODE_HEADER_SIZE,fdIn);
if (count<CODE_HEADER_SIZE)
{
printf("decodeFile: file read error!\n");
fclose(fdIn);
return;
}
memcpy(header,line,CODE_HEADER_SIZE);
if (dataIn!=0)
free(dataIn);
dataIn = malloc(header->sizeHUF);
dataSize=0;
while( (count=fread(line, 1, minim(1024,header->sizeHUF-dataSize), fdIn))>0)
{
memcpy(&(dataIn[dataSize]),line,count);
dataSize+=count;
}
}
fclose(fdIn);
printf("DECODE header (%dx%d, qual=%d, col=%d, sizeRLE=%d, sizeHUF=%d)\n",
header->width,header->height,header->quality,
header->is_color,header->sizeRLE,header->sizeHUF);
decode(header, dataIn, decoded);
}
void idct(code_header_t *header, int8_t* dct_decoded, uint8_t *recovered, uint8_t bufShift, uint8_t *qtable)
{
int32_t i,j;
for (i=0; i<header->width>>3; i++)
for (j=0; j<header->height>>3; j++)
idctNew(i,j,header->width*header->height>>6,
dct_decoded,recovered,bufShift,
qtable,header->quality,header->width);
}
void decodeJpegFile(char *filename, uint8_t *recovered, code_header_t *header,uint16_t width, uint16_t height)
//void decodeJpegFile(char *filename, uint16_t *recovered, code_header_t *header,uint16_t width, uint16_t height)
{
int32_t ycc_rgb_table[YCC_RGB_TABLE_SIZE]; ycc_rgb_init(ycc_rgb_table);
int8_t dct_decoded[width*height];
// int16_t dct_decoded[width*height];
decodeFile(filename,dct_decoded,header,1);
if (header->is_color)
{
idct(header, dct_decoded, recovered, 3, QUANT_TABLE);
decodeFile(filename,dct_decoded,header,2);
idct(header, dct_decoded, &recovered[1], 3, QUANT_TABLE);
decodeFile(filename,dct_decoded,header,3);
idct(header, dct_decoded, &recovered[2], 3, QUANT_TABLE);
ycc_rgb_convert(recovered,recovered,ycc_rgb_table,header->width*3,header->height);
}
else
idct(header, dct_decoded, recovered, 1, QUANT_TABLE);
FILE *fd_tmp=0;
if (!(fd_tmp = fopen("decoded.huf", "w")) ){
printf("decodeJpegFile: Can't open decoded.huf file for writing\n");
return;
}
fwrite(dct_decoded,1,width*height,fd_tmp);
fclose(fd_tmp);printf("written decoded.huf file\n");
}
void decodeJpegBytes(uint8_t *dataIn, uint32_t dataSize, uint8_t *recovered, code_header_t *header,uint16_t width,uint16_t height)
{
int32_t ycc_rgb_table[YCC_RGB_TABLE_SIZE];
ycc_rgb_init(ycc_rgb_table);
int8_t dct_decoded[width*height];
// int16_t dct_decoded[width*height];
//get header
decodeBytes(dataIn, dct_decoded, header);
if (header->is_color)
{
//uint16_t dataSize=header->totalSize;
idcti(header, dct_decoded, recovered, 3, QUANT_TABLE);
uint32_t idx=header->sizeHUF+CODE_HEADER_SIZE;
if (dataSize>idx+1200)
{
decodeBytes(&dataIn[idx],dct_decoded,header);
idct(header, dct_decoded, &recovered[1], 3, QUANT_TABLE);
idx+=header->sizeHUF+CODE_HEADER_SIZE;
if (dataSize>idx+1200)
{
decodeBytes(&dataIn[idx],dct_decoded,header);
idct(header, dct_decoded, &recovered[2], 3, QUANT_TABLE);
}
ycc_rgb_convert(recovered,recovered,ycc_rgb_table,header->width*3,header->height);
}
else //for output as bw img
{
int i, ibound=header->height*header->width;
for (i=1; i<ibound; ++i)
recovered[i]=recovered[i*3];
header->is_color=0;
}
header->totalSize=dataSize;
}
else
idct(header, dct_decoded, recovered, 1, QUANT_TABLE);
}
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/util/collect/sfcomm.c | <reponame>tinyos-io/tinyos-3.x-contrib
#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 <sys/types.h>
#include "sfsource.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_END_DATA_COLLECTION_SESSION 22
#define AM_BUNDLE_INDEX_ACK 23
///////////////////////////////////////////////////////////////////////////////////////////////////
// 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)
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;
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);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// This is where the Magic Happens
///////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
int fd;
int mote_addr;
TOS_write_t tos_write;
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);
}
mote_addr = atoi(argv[3]);
tos_write.fd = fd;
tos_write.mote_addr = mote_addr;
//mote_write( (void *) &tos_write);
pthread_create(write_thread, &pthread_custom_attr, mote_write, &tos_write);
pthread_create(read_thread, &pthread_custom_attr, mote_read, &tos_write);
pthread_join(write_thread,NULL);
pthread_join(read_thread,NULL);
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | kasetsart/tos/platforms/iwing-mrf/platform_message.h | <reponame>tinyos-io/tinyos-3.x-contrib
/**
* Defining the platform-independently named packet structures to be the
* chip-specific MRF24J40 packet structures.
*
* @author
* <NAME> (<EMAIL>)
*/
#ifndef PLATFORM_MESSAGE_H
#define PLATFORM_MESSAGE_H
#include "mrf24.h"
#include "Serial.h"
typedef union message_header
{
mrf24_header_t mrf24;
serial_header_t serial;
} message_header_t;
typedef union message_footer
{
mrf24_footer_t mrf24;
} message_footer_t;
typedef union message_metadata
{
mrf24_metadata_t mrf24;
serial_metadata_t serial;
} message_metadata_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | uob/tossdr/ucla/gnuradio-802.15.4-demodulation/src/lib/ucla_sos_packet_sink.h | /* -*- c++ -*- */
/*
* Copyright 2005 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., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef INCLUDED_UCLA_SOS_PACKET_SINK_H
#define INCLUDED_UCLA_SOS_PACKET_SINK_H
#include <gr_sync_block.h>
#include <gr_msg_queue.h>
class ucla_sos_packet_sink;
typedef boost::shared_ptr<ucla_sos_packet_sink> ucla_sos_packet_sink_sptr;
ucla_sos_packet_sink_sptr
ucla_make_sos_packet_sink (const std::vector<unsigned char>& sync_vector,
gr_msg_queue_sptr target_queue,
int threshold = -1 // -1 -> use default
);
/*!
* \brief process received bits looking for packet sync, header, and process bits into packet
* \ingroup sink
*/
class ucla_sos_packet_sink : public gr_sync_block
{
friend ucla_sos_packet_sink_sptr
ucla_make_sos_packet_sink (const std::vector<unsigned char>& sync_vector,
gr_msg_queue_sptr target_queue,
int threshold);
private:
enum state_t {STATE_SYNC_SEARCH, STATE_HAVE_SYNC, STATE_HAVE_HEADER};
static const int MSG_LEN_POS = 8+1; // 8 byte sos header, 1 byte AM type
static const int MAX_PKT_LEN = 128 - MSG_LEN_POS - 1; // remove header and CRC
gr_msg_queue_sptr d_target_queue; // where to send the packet when received
unsigned long long d_sync_vector; // access code to locate start of packet
unsigned int d_threshold; // how many bits may be wrong in sync vector
unsigned char d_manchester; // do we use manchester encoding or not
state_t d_state;
unsigned long long d_shift_reg; // used to look for sync_vector
unsigned int d_header; // header bits
int d_headerbitlen_cnt; // how many so far
unsigned char d_packet[MAX_PKT_LEN]; // assembled payload
unsigned char d_packet_byte; // byte being assembled
unsigned char d_packet_byte_manchester; // byte which is needed for manchester encoding
int d_packet_byte_index; // which bit of d_packet_byte we're working on
int d_packetlen; // length of packet
int d_packetlen_cnt; // how many so far
int d_payload_cnt; // how many bytes in payload
protected:
ucla_sos_packet_sink(const std::vector<unsigned char>& sync_vector,
gr_msg_queue_sptr target_queue,
int threshold);
void enter_search();
void enter_have_sync();
void enter_have_header(int payload_len);
int slice(float x) { return x > 0 ? 1 : 0; }
bool header_ok()
{
// might do some checks on the header later...
return 1;
}
unsigned char manchester_decode(unsigned char b1, unsigned char b2){
unsigned char t, b;
int errors = 0;
for (unsigned char i = 0; i < 8; i += 2){
t = (b1 >> (6 - i)) & 0x3;
if ( t == 1 ){
b = (b << 1) | 0;
} else if ( t == 2 ){
b = (b << 1) | 1;
} else {
// mistake in manchester encoding encode as 0
b = (b << 1) | 0;
errors += 1;
}
}
for (unsigned char i = 0; i < 8; i += 2){
t = (b2 >> (6 - i)) & 0x3;
if ( t == 1 ){
b = (b << 1) | 0;
} else if ( t == 2 ){
b = (b << 1) | 1;
} else {
// mistake in manchester encoding encode as 0
b = (b << 1) | 0;
errors += 1;
}
}
return b;
}
public:
~ucla_sos_packet_sink();
int work(int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items);
//! return true if we detect carrier
bool carrier_sensed() const
{
return d_state != STATE_SYNC_SEARCH;
}
};
#endif /* INCLUDED_GR_PACKET_SINK_H */
|
tinyos-io/tinyos-3.x-contrib | intelmote2/support/sdk/c/camera_cmd/img_stat.c | <reponame>tinyos-io/tinyos-3.x-contrib
/**
* This file is automatically generated by mig. DO NOT EDIT THIS FILE.
* This file implements the functions for encoding and decoding the
* 'img_stat' message type. See img_stat.h for more details.
*/
#include <message.h>
#include "img_stat.h"
uint16_t img_stat_node_id_get(tmsg_t *msg)
{
return tmsg_read_ube(msg, 0, 16);
}
void img_stat_node_id_set(tmsg_t *msg, uint16_t value)
{
tmsg_write_ube(msg, 0, 16, value);
}
uint8_t img_stat_type_get(tmsg_t *msg)
{
return tmsg_read_ube(msg, 16, 8);
}
void img_stat_type_set(tmsg_t *msg, uint8_t value)
{
tmsg_write_ube(msg, 16, 8, value);
}
uint16_t img_stat_width_get(tmsg_t *msg)
{
return tmsg_read_ube(msg, 24, 16);
}
void img_stat_width_set(tmsg_t *msg, uint16_t value)
{
tmsg_write_ube(msg, 24, 16, value);
}
uint16_t img_stat_height_get(tmsg_t *msg)
{
return tmsg_read_ube(msg, 40, 16);
}
void img_stat_height_set(tmsg_t *msg, uint16_t value)
{
tmsg_write_ube(msg, 40, 16, value);
}
uint32_t img_stat_data_size_get(tmsg_t *msg)
{
return tmsg_read_ube(msg, 56, 32);
}
void img_stat_data_size_set(tmsg_t *msg, uint32_t value)
{
tmsg_write_ube(msg, 56, 32, value);
}
uint32_t img_stat_timeAcq_get(tmsg_t *msg)
{
return tmsg_read_ube(msg, 88, 32);
}
void img_stat_timeAcq_set(tmsg_t *msg, uint32_t value)
{
tmsg_write_ube(msg, 88, 32, value);
}
uint32_t img_stat_timeProc_get(tmsg_t *msg)
{
return tmsg_read_ube(msg, 120, 32);
}
void img_stat_timeProc_set(tmsg_t *msg, uint32_t value)
{
tmsg_write_ube(msg, 120, 32, value);
}
|
tinyos-io/tinyos-3.x-contrib | stanford-lgl/tos/chips/ov7649/OV7649.h | <gh_stars>1-10
/*
* Copyright (c) 2006 Stanford University.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
* - Neither the name of the Stanford University nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STANFORD
* UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @brief Driver module for the OmniVision OV7649 Camera
* @author
* <NAME> (<EMAIL>)
* <NAME> (<EMAIL>)
*/
/**
* @brief Ported to TOS2
* @author <NAME> (<EMAIL>)
*/
#ifndef _OV7649_H
#define _OV7649_H
#define MAX_OV7649_REG 0x80
#define ENABLE 1
#define DISABLE 0
#define OVWRITE 0x42
#define OVREAD 0x43
#define GAIN 0x00
#define BLUE 0x01
#define RED 0x02
#define SAT 0x03
#define HUE 0x04
#define CWF 0x05
#define BRT 0x06
#define PID 0x0A
#define VER 0x0B
#define AECH 0x10
#define CLKRC 0x11 // HSYNC polarity
#define COMA 0x12
#define COMB 0x13
#define COMC 0x14 // resolution and HREF polarity
#define COMD 0x15 // ydata and pclk polarity
#define REG16 0x16
#define PSHFT 0x1B // pixel delay after href
#define REG1E 0x1E
#define FACT 0x1F // rgb format control
#define COMF 0x26 // byte-oder in ydata
#define COMG 0x27
#define COMH 0x28
#define FRARH 0x2A // FRA[9:0] = FRARH[6:5](msb) + FRARL[7:0](lsb)
#define FRARL 0x2B
#define COMJ 0x2D
#define RMCO 0x6C
#define GMCO 0x6D
#define BMCO 0x6E
#define COML 0x71 // gate PCLK with HREF and set HSYNC delay msb
#define HSDYR 0x72 // HSYNC rising edge delay lsb
#define HSDYF 0x73 // HSYNC falling edge delay lsb ( 0 to 762 pixel delays )
#define COMM 0x74
#define COMN 0x75 // vertical flip enable
#define REG79 0x79 //! This is reserved, but mentioned in the OVT Effects document (for OV7640 ?)
#define REG7A 0x7A //! This is reserved, but mentioned in the OVT Effects document
#define HSTRT 0x17
#define HSTOP 0x18
#define VSTRT 0x19
#define VSTOP 0x1A
typedef struct {
uint8_t config;
} __attribute__ ((packed)) ov_config_t;
typedef struct {
uint8_t color;
uint8_t config;
uint8_t stat;
} __attribute__ ((packed)) ov_stat_t;
enum {
COLOR_RGB565_XYZ,
COLOR_UYVY_XYZ,
COLOR_RGB565,
COLOR_UYVY,
COLOR_8BITGRAY,
COLOR_1BITBW,
};
enum {
OV_CONFIG_YUV,
OV_CONFIG_RGB,
};
enum {
//OV_STAT_IDLE = 0x00,
OV_STAT_CAPTURE = 0x01,
OV_STAT_PROCESS = 0x02,
OV_STAT_ERROR = 0x04,
OV_STAT_FLIP = 0x10,
};
#define OV_STAT_FLIP_BIT OV_STAT_FLIP
#define PWDN_INTERVAL 1024
#define RESET_INTERVAL 1024
#define CRYSTAL_INTERVAL 4096
#endif /* _OV7649_H */
|
tinyos-io/tinyos-3.x-contrib | diku/common/lib/compression/lz77_diff.h | #define DIFFERENCE
#include "../../tools/compression/lz77/lz77_comp.c"
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/driver/get_descriptor.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 get_descriptor(libusb_device_t *dev,
void *buffer, int size, int type, int recipient,
int index, int language_id, int *received, int timeout)
{
NTSTATUS status = STATUS_SUCCESS;
URB urb;
DEBUG_PRINT_NL();
DEBUG_MESSAGE("get_descriptor(): buffer size %d", size);
DEBUG_MESSAGE("get_descriptor(): type %04d", type);
DEBUG_MESSAGE("get_descriptor(): recipient %04d", recipient);
DEBUG_MESSAGE("get_descriptor(): index %04d", index);
DEBUG_MESSAGE("get_descriptor(): language id %04d", language_id);
DEBUG_MESSAGE("get_descriptor(): timeout %d", timeout);
memset(&urb, 0, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST));
switch(recipient)
{
case USB_RECIP_DEVICE:
urb.UrbHeader.Function = URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE;
break;
case USB_RECIP_INTERFACE:
urb.UrbHeader.Function = URB_FUNCTION_GET_DESCRIPTOR_FROM_INTERFACE;
break;
case USB_RECIP_ENDPOINT:
urb.UrbHeader.Function = URB_FUNCTION_GET_DESCRIPTOR_FROM_ENDPOINT;
break;
default:
DEBUG_ERROR("get_descriptor(): invalid recipient");
return STATUS_INVALID_PARAMETER;
}
urb.UrbHeader.Length = sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST);
urb.UrbControlDescriptorRequest.TransferBufferLength = size;
urb.UrbControlDescriptorRequest.TransferBuffer = buffer;
urb.UrbControlDescriptorRequest.DescriptorType = (UCHAR)type;
urb.UrbControlDescriptorRequest.Index = (UCHAR)index;
urb.UrbControlDescriptorRequest.LanguageId = (USHORT)language_id;
status = call_usbd(dev, &urb, IOCTL_INTERNAL_USB_SUBMIT_URB, timeout);
if(!NT_SUCCESS(status) || !USBD_SUCCESS(urb.UrbHeader.Status))
{
DEBUG_ERROR("get_descriptor(): getting descriptor "
"failed: status: 0x%x, urb-status: 0x%x",
status, urb.UrbHeader.Status);
*received = 0;
}
else
{
*received = urb.UrbControlDescriptorRequest.TransferBufferLength;
}
return status;
}
USB_CONFIGURATION_DESCRIPTOR *
get_config_descriptor(libusb_device_t *dev, int value, int *size)
{
NTSTATUS status;
USB_CONFIGURATION_DESCRIPTOR *desc = NULL;
USB_DEVICE_DESCRIPTOR device_descriptor;
int i;
volatile int desc_size;
status = get_descriptor(dev, &device_descriptor,
sizeof(USB_DEVICE_DESCRIPTOR),
USB_DEVICE_DESCRIPTOR_TYPE,
USB_RECIP_DEVICE,
0, 0, size, LIBUSB_DEFAULT_TIMEOUT);
if(!NT_SUCCESS(status) || *size != sizeof(USB_DEVICE_DESCRIPTOR))
{
DEBUG_ERROR("get_config_descriptor(): getting device descriptor failed");
return NULL;
}
if(!(desc = ExAllocatePool(NonPagedPool,
sizeof(USB_CONFIGURATION_DESCRIPTOR))))
{
DEBUG_ERROR("get_config_descriptor(): memory allocation error");
return NULL;
}
for(i = 0; i < device_descriptor.bNumConfigurations; i++)
{
if(!NT_SUCCESS(get_descriptor(dev, desc,
sizeof(USB_CONFIGURATION_DESCRIPTOR),
USB_CONFIGURATION_DESCRIPTOR_TYPE,
USB_RECIP_DEVICE,
i, 0, size, LIBUSB_DEFAULT_TIMEOUT)))
{
DEBUG_ERROR("get_config_descriptor(): getting configuration "
"descriptor failed");
break;
}
if(desc->bConfigurationValue == value)
{
desc_size = desc->wTotalLength;
ExFreePool(desc);
if(!(desc = ExAllocatePool(NonPagedPool, desc_size)))
{
DEBUG_ERROR("get_config_descriptor(): memory allocation error");
break;
}
if(!NT_SUCCESS(get_descriptor(dev, desc, desc_size,
USB_CONFIGURATION_DESCRIPTOR_TYPE,
USB_RECIP_DEVICE,
i, 0, size, LIBUSB_DEFAULT_TIMEOUT)))
{
DEBUG_ERROR("get_config_descriptor(): getting configuration "
"descriptor failed");
break;
}
return desc;
}
}
if(desc)
{
ExFreePool(desc);
}
return NULL;
}
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/driver/dispatch.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 DDKAPI dispatch(DEVICE_OBJECT *device_object, IRP *irp)
{
libusb_device_t *dev = device_object->DeviceExtension;
switch(IoGetCurrentIrpStackLocation(irp)->MajorFunction)
{
case IRP_MJ_PNP:
return dispatch_pnp(dev, irp);
case IRP_MJ_POWER:
return dispatch_power(dev, irp);
}
/* since this driver may run as an upper filter we have to check whether */
/* the IRP is sent to this device object or to the lower one */
if(accept_irp(dev, irp))
{
switch(IoGetCurrentIrpStackLocation(irp)->MajorFunction)
{
case IRP_MJ_DEVICE_CONTROL:
if(dev->is_started)
{
return dispatch_ioctl(dev, irp);
}
else /* not started yet */
{
return complete_irp(irp, STATUS_INVALID_DEVICE_STATE, 0);
}
case IRP_MJ_CREATE:
if(dev->is_started)
{
if(InterlockedIncrement(&dev->ref_count) == 1)
{
if(dev->power_state.DeviceState != PowerDeviceD0)
{
/* power up the device, block until the call */
/* completes */
power_set_device_state(dev, PowerDeviceD0, TRUE);
}
}
return complete_irp(irp, STATUS_SUCCESS, 0);
}
else /* not started yet */
{
return complete_irp(irp, STATUS_INVALID_DEVICE_STATE, 0);
}
case IRP_MJ_CLOSE:
if(!InterlockedDecrement(&dev->ref_count))
{
/* release all interfaces when the last handle is closed */
release_all_interfaces(dev);
}
return complete_irp(irp, STATUS_SUCCESS, 0);
case IRP_MJ_CLEANUP:
return complete_irp(irp, STATUS_SUCCESS, 0);
default:
return complete_irp(irp, STATUS_NOT_SUPPORTED, 0);
}
}
else /* the IRP is for the lower device object */
{
return pass_irp_down(dev, irp, NULL, NULL);
}
}
|
tinyos-io/tinyos-3.x-contrib | tcd/powertossim-z/tinyos_files/tinyos-2.0.2/tos/lib/tossim/csma.h | <reponame>tinyos-io/tinyos-3.x-contrib<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."
*/
/**
*
* Configuration parameters for a CSMA link.
*
* @author <NAME>
* @date Dec 10 2005
*/
#ifndef CSMA_H_INCLUDED
#define CSMA_H_INCLUDED
class Csma {
public:
Csma();
~Csma();
int initHigh();
int initLow();
int high();
int low();
int symbolsPerSec();
int bitsPerSymbol();
int preambleLength(); // in symbols
int exponentBase();
int maxIterations();
int minFreeSamples();
int rxtxDelay();
int ackTime(); // in symbols
void setInitHigh(int val);
void setInitLow(int val);
void setHigh(int val);
void setLow(int val);
void setSymbolsPerSec(int val);
void setBitsBerSymbol(int val);
void setPreambleLength(int val); // in symbols
void setExponentBase(int val);
void setMaxIterations(int val);
void setMinFreeSamples(int val);
void setRxtxDelay(int val);
void setAckTime(int val); // in symbols int
}
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/quanto/tos/chips/msp430/msp430quantoconsts.h | <reponame>tinyos-io/tinyos-3.x-contrib
#ifndef _MSP430QUANTOCONSTS_H
#define _MSP430QUANTOCONSTS_H
//Quanto: these are the primary proxy activities for each
// interrupt that TinyOS uses from the MSP430.
enum {
ACT_PXY_ADC = 0x40,
ACT_PXY_DACDMA = 0x41,
ACT_PXY_NMI = 0x42,
ACT_PXY_PORT1 = 0x43,
ACT_PXY_PORT2 = 0x44,
ACT_PXY_TIMERA0 = 0x45,
ACT_PXY_TIMERA1 = 0x46,
ACT_PXY_TIMERB0 = 0x47,
ACT_PXY_TIMERB1 = 0x48,
ACT_PXY_UART0RX = 0x49,
ACT_PXY_UART0TX = 0x4A,
ACT_PXY_UART1RX = 0x4B,
ACT_PXY_UART1TX = 0x4C,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | antlab-polimi/dpcm_C/huffmanUncompress.c | <gh_stars>1-10
/*************************************************************************
* Name: huffman.c
* Author: <NAME>
* Description: Huffman coder/decoder implementation.
* Reentrant: Yes
*
* This is a very straight forward implementation of a Huffman coder and
* decoder.
*
* Primary flaws with this primitive implementation are:
* - Slow bit stream implementation
* - Maximum tree depth of 32 (the coder aborts if any code exceeds a
* size of 32 bits). If I'm not mistaking, this should not be possible
* unless the input buffer is larger than 2^32 bytes, which is not
* supported by the coder anyway (max 2^32-1 bytes can be specified with
* an unsigned 32-bit integer).
*
* On the other hand, there are a few advantages of this implementation:
* - The Huffman tree is stored in a very compact form, requiring only
* 10 bits per symbol (for 8 bit symbols), meaning a maximum of 320
* bytes overhead.
* - The code should be fairly easy to follow, if you are familiar with
* how the Huffman compression algorithm works.
*
* Possible improvements (probably not worth it):
* - Partition the input data stream into blocks, where each block has
* its own Huffman tree. With variable block sizes, it should be
* possible to find locally optimal Huffman trees, which in turn could
* reduce the total size.
* - Allow for a few different predefined Huffman trees, which could
* reduce the size of a block even further.
*-------------------------------------------------------------------------
* Copyright (c) 2003-2006 <NAME>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
* <NAME>
* marcus.geelnard at home.se
*************************************************************************/
/*************************************************************************
* Types used for Huffman coding
*************************************************************************/
#include <inttypes.h>
typedef struct {
uint8_t *BytePtr;
uint16_t BitPos;
} huff_bitstream_t;
typedef struct {
int16_t Symbol;
uint16_t Count;
uint16_t Code;
uint16_t Bits;
} huff_sym_t;
typedef struct huff_encodenode_struct huff_encodenode_t;
struct huff_encodenode_struct {
huff_encodenode_t *ChildA, *ChildB;
int16_t Count;
int16_t Symbol;
};
typedef struct huff_decodenode_struct huff_decodenode_t;
struct huff_decodenode_struct {
huff_decodenode_t *ChildA, *ChildB;
int16_t Symbol;
};
/*************************************************************************
* Constants for Huffman decoding
*************************************************************************/
/* The maximum number of nodes in the Huffman tree is 2^(8+1)-1 = 511 */
#define MAX_TREE_NODES 511
/*************************************************************************
* INTERNAL FUNCTIONS *
*************************************************************************/
/*************************************************************************
* _Huffman_InitBitstream() - Initialize a bitstream.
*************************************************************************/
static void _Huffman_InitBitstream( huff_bitstream_t *stream,
uint8_t *buf )
{
stream->BytePtr = buf;
stream->BitPos = 0;
}
/*************************************************************************
* _Huffman_ReadBit() - Read one bit from a bitstream.
*************************************************************************/
static uint16_t _Huffman_ReadBit( huff_bitstream_t *stream )
{
uint16_t x, bit;
uint8_t *buf;
/* Get current stream state */
buf = stream->BytePtr;
bit = stream->BitPos;
/* Extract bit */
x = (*buf & (1<<(7-bit))) ? 1 : 0;
bit = (bit+1) & 7;
if( !bit )
{
++ buf;
}
/* Store new stream state */
stream->BitPos = bit;
stream->BytePtr = buf;
return x;
}
/*************************************************************************
* _Huffman_Read8Bits() - Read eight bits from a bitstream.
*************************************************************************/
static uint16_t _Huffman_Read8Bits( huff_bitstream_t *stream )
{
uint16_t x, bit;
uint8_t *buf;
/* Get current stream state */
buf = stream->BytePtr;
bit = stream->BitPos;
/* Extract byte */
x = (*buf << bit) | (buf[1] >> (8-bit));
++ buf;
/* Store new stream state */
stream->BytePtr = buf;
return x;
}
/*************************************************************************
* _Huffman_RecoverTree() - Recover a Huffman tree from a bitstream.
*************************************************************************/
static huff_decodenode_t * _Huffman_RecoverTree( huff_decodenode_t *nodes,
huff_bitstream_t *stream, uint16_t *nodenum )
{
huff_decodenode_t * this_node;
/* Pick a node from the node array */
this_node = &nodes[*nodenum];
*nodenum = *nodenum + 1;
/* Clear the node */
this_node->Symbol = -1;
this_node->ChildA = (huff_decodenode_t *) 0;
this_node->ChildB = (huff_decodenode_t *) 0;
/* Is this a leaf node? */
if( _Huffman_ReadBit( stream ) )
{
/* Get symbol from tree description and store in lead node */
this_node->Symbol = _Huffman_Read8Bits( stream );
// this_node->Symbol = _Huffman_Read16Bits( stream );
return this_node;
}
/* Get branch A */
this_node->ChildA = _Huffman_RecoverTree( nodes, stream, nodenum );
/* Get branch B */
this_node->ChildB = _Huffman_RecoverTree( nodes, stream, nodenum );
return this_node;
}
/*************************************************************************
* PUBLIC FUNCTIONS *
*************************************************************************/
/*************************************************************************
* Huffman_Uncompress() - Uncompress a block of data using a Huffman
* decoder.
* in - Input (compressed) buffer.
* out - Output (uncompressed) buffer. This buffer must be large
* enough to hold the uncompressed data.
* insize - Number of input bytes.
* outsize - Number of output bytes.
*************************************************************************/
void Huffman_Uncompress( uint8_t *in, uint8_t *out,
uint16_t insize, uint16_t outsize )
{
huff_decodenode_t nodes[MAX_TREE_NODES], *root, *node;
huff_bitstream_t stream;
uint16_t k, node_count;
uint8_t *buf;
/* Do we have anything to decompress? */
if( insize < 1 ) return;
/* Initialize bitstream */
_Huffman_InitBitstream( &stream, in );
/* Recover Huffman tree */
node_count = 0;
root = _Huffman_RecoverTree( nodes, &stream, &node_count );
/* Decode input stream */
buf = out;
for( k = 0; k < outsize; ++ k )
{
/* Traverse tree until we find a matching leaf node */
node = root;
while( node->Symbol < 0 )
{
/* Get next node */
if( _Huffman_ReadBit( &stream ) )
node = node->ChildB;
else
node = node->ChildA;
}
/* We found the matching leaf node and have the symbol */
*buf ++ = (uint8_t) node->Symbol;
}
}
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/util/tinyrely/TinyRely.h |
#include <AM.h>
#ifndef TINYRELY_H_INCLUDED
#define TINYRELY_H_INCLUDED
#ifndef RELY_HEADER_LENGTH
#define RELY_HEADER_LENGTH 6
#endif
#ifndef RELY_PAYLOAD_LENGTH
#define RELY_PAYLOAD_LENGTH (TOSH_DATA_LENGTH-RELY_HEADER_LENGTH)
#endif
#ifndef RELY_MAX_CONNECTIONS
#define RELY_MAX_CONNECTIONS 3
#endif
#ifndef RELY_UID_INVALID
#define RELY_UID_INVALID 0
#endif
#ifndef RELY_IDX_INVALID
#define RELY_IDX_INVALID -1
#endif
#define RELY_TIME_STEP 300
#define RELY_CONN_TIMEOUT 15000 //reset connection if no
#define RELY_RESEND_TIMEOUT 500
typedef struct ConnStr {
bool valid;
bool pending;
bool sending;
bool resending;
bool full;
bool closing;
uint8_t count;
uint8_t suid;
uint8_t duid;
uint16_t addr;
uint8_t txseq;
uint8_t rxseq;
TOS_Msg txbuf;
TOS_Msg rxbuf;
TOS_Msg ackbuf;
} ConnStr;
typedef struct ConnMsg {
uint16_t src;
uint8_t suid; //chosen by connection requestor
uint8_t duid; //assigned by connection acceptor
uint8_t type; //CONN_TYPE_XXXX
uint8_t ok; //RELY_XXXXX
} __attribute((packed)) ConnMsg;
typedef struct TinyRelyMsg {
uint16_t src;
uint8_t suid;
uint8_t duid;
uint8_t seq;
uint8_t length;
uint8_t data[RELY_PAYLOAD_LENGTH];
} __attribute((packed)) TinyRelyMsg;
typedef struct TinyRelyAck {
uint16_t src;
uint8_t suid;
uint8_t duid;
uint8_t seq;
uint8_t ok; //RELY_XXXXX
} __attribute((packed)) TinyRelyAck;
enum {
CONN_TYPE_REQUEST=0,
CONN_TYPE_ACK = 1,
CONN_TYPE_CLOSE = 2
};
enum {
RELY_OK = 0,
RELY_DUP = 1,
RELY_FULL= 2,
RELY_ERR = 3
};
enum {
AM_TINYRELYCONNECT = 0xE0,
AM_TINYRELYMSG = 0xE1,
AM_TINYRELYACK = 0xE2
};
typedef struct RelySegment
{
uint8_t length;
uint8_t data[RELY_PAYLOAD_LENGTH];
} RelySegment;
typedef ConnMsg* ConnMsgPtr;
typedef TinyRelyMsg* TinyRelyMsgPtr;
typedef TinyRelyAck* TinyRelyAckPtr;
typedef RelySegment* RelySegmentPtr;
typedef uint8_t relyresult;
#endif
|
tinyos-io/tinyos-3.x-contrib | tinymulle/tos/platforms/mulle/platform_message.h | /**
* @author <NAME>
*/
#ifndef PLATFORM_MESSAGE_H
#define PLATFORM_MESSAGE_H
#include "Serial.h"
#include <RF230ActiveMessage.h>
typedef union message_header {
rf230packet_header_t rf230;
serial_header_t serial;
} message_header_t;
typedef union message_footer {
rf230packet_footer_t rf230;
} message_footer_t;
typedef union message_metadata {
rf230packet_metadata_t rf230;
} message_metadata_t;
#endif // PLATFORM_MESSAGE_H
|
tinyos-io/tinyos-3.x-contrib | antlab-polimi/dpcm_C/decodeZeros.h | <gh_stars>1-10
uint32_t decodeZeros(uint8_t *dataIn, unsigned char *dataOut,
uint32_t size, uint32_t maxSize)
{
uint32_t i,r,j, idx=0;
r=0;
for (i=0; i<size; i++)
{
if (dataIn[r] == 0 && (r+1)<size)
{
// doppio zero: zeri fino a fine file
if(dataIn[(r+1)]==0){
while (idx<maxSize)
dataOut[idx++]=0;
return idx;
}
for (j=0; j<dataIn[(r+1)]; j++)
dataOut[idx++]=0;
r=r+2;
}
else if(dataIn[r]!=0 && (r+1)<=size)
{
int8_t value=dataIn[r];
dataOut[idx++]=value;
r=r+1;
}
else{
printf("\nZero length decoding error..\n");
return 0;
}
}
return idx;
}
static inline void decodeDC(uint8_t *dataIn, uint8_t *dataOut, uint16_t dataSize)
{
uint16_t i;
dataOut[0]=dataIn[0];
for (i=1; i<dataSize; i++)
dataOut[i]=dataOut[i-1]-dataIn[i];
}
|
tinyos-io/tinyos-3.x-contrib | intelmote2/tos/chips/pxa27x/mmu.h | /**
* author <NAME>
**/
#ifndef __MMU_H__
#define __MMU_H__
/**
* Initialize the processor's MMU unit. The page table to use and some
other parameters are defined in platform/pxa27x/mmu_table.s
**/
void initMMU();
/**
* Place the attached flash chip into synchronous mode
**/
void initSyncFlash() __attribute__ ((long_call, section(".data")));
/**
* Enable the Instruction Cache. This function currently also enabled
* the branch target buffer
**/
void enableICache();
/**
* Enable the data cache.
**/
void enableDCache();
/**
* disable the data cache. In order to ensure cache coherency, this function
* will also globally clean and invalidate the cache
**/
void disableDCache();
/**
* invalidate the data cache for the buffer pointed to by address of length
* numbytes.
*
* Notes:
* - invalidate = make cache lines invalid
* - numbytes will be rounded up to the nearest multiple of 32.
* - Address is required to be a virtual address
*
**/
void invalidateDCache(uint8_t *address, int32_t numbytes);
/**
* clean the data cache for the buffer pointed to by address of length
* numbytes.
*
* Notes:
* - clean = write back to memory if dirty
* - numbytes will be rounded up to the nearest multiple of 32.
* - Address is required to be a virtual address
*
**/
void cleanDCache(uint8_t *address, int32_t numbytes);
/**
* globally clean (flush to memory if dirty) and invalidate the data cache
*
**/
void globalCleanAndInvalidateDCache();
#endif
|
tinyos-io/tinyos-3.x-contrib | wsu/telosw/teloswplatform/platform_message.h |
#ifndef PLATFORM_MESSAGE_H
#define PLATFORM_MESSAGE_H
#include "Blaze.h"
#include "Serial.h"
typedef union message_header {
blaze_header_t blazeHeader;
serial_header_t serial;
} message_header_t;
typedef union TOSRadioFooter {
blaze_footer_t blazeFooter;
} message_footer_t;
typedef union TOSRadioMetadata {
blaze_metadata_t blazeMetadata;
} message_metadata_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/support/sdk/c/blip/interface/logging.h | <reponame>tinyos-io/tinyos-3.x-contrib
/*
* "Copyright (c) 2008 The Regents of the University of California.
* All rights reserved."
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written agreement is
* hereby granted, provided that the above copyright notice, the following
* two paragraphs and the author appear in all copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
* OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
* CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
*/
#ifndef LOGGING_H_
#define LOGGING_H_
#include <stdio.h>
// SDH : log levels defined here
// also edit the log names in logging.h
typedef enum {
LOGLVL_DEBUG = 0,
LOGLVL_INFO = 1,
LOGLVL_WARN = 2,
LOGLVL_ERROR = 3,
LOGLVL_FATAL = 4,
} loglevel_t;
extern const char *log_names[5];
extern loglevel_t log_level;
extern FILE *log_dest;
void log_init();
loglevel_t log_setlevel(loglevel_t l);
loglevel_t log_getlevel();
void log_log (loglevel_t level, const char *fmt, ...);
void log_fatal_perror(const char *msg);
void log_clear (loglevel_t level, const char *fmt, ...);
#define debug(fmt, args...) \
log_log(LOGLVL_DEBUG, fmt, ## args)
#define info(fmt, args...) \
log_log(LOGLVL_INFO, fmt, ## args)
#define warn(fmt, args...) \
log_log(LOGLVL_WARN, fmt, ## args)
#define error(fmt, args...) \
log_log(LOGLVL_ERROR, fmt, ## args)
#define fatal(fmt, args...) \
log_log(LOGLVL_FATAL, fmt, ## args)
#define log_fprintf(X, FMT, ...) ;
#define ISO8601_FMT(ltime, tv) "%04d-%02d-%02dT%02d:%02d:%02d.%03d%s", \
(ltime)->tm_year+1900, (ltime)->tm_mon+1, (ltime)->tm_mday, \
(ltime)->tm_hour, (ltime)->tm_min, (ltime)->tm_sec, (int)(tv)->tv_usec/ 1000, \
tzname[0]
void log_dump_serial_packet(unsigned char *packet, const int len);
/* the number of lines of log history to buffer */
#define LOGHISTSIZ 500
/* the length of each buffered log line; longer entries are truncated */
#define LOGLINESIZ 100
/* shell command for log history */
void log_show_log(int fd, int argc, char **argv);
#endif
|
tinyos-io/tinyos-3.x-contrib | usc/senzip/SenZip_v1.0/senzip/TreeRouting.h | #ifndef _TREE_ROUTING_H
#define _TREE_ROUTING_H
enum {
AM_TREE_ROUTING_CONTROL = 0xCE,
BEACON_INTERVAL = 8192,
INVALID_ADDR = TOS_BCAST_ADDR,
ETX_THRESHOLD = 50, // link quality=20% -> ETX=5 -> Metric=50
PARENT_SWITCH_THRESHOLD = 15,
MAX_METRIC = 0xFFFF,
};
typedef struct {
am_addr_t parent;
uint16_t etx;
bool haveHeard;
bool congested;
/* senzip */
uint8_t hopDepth;
} route_info_t;
typedef struct {
am_addr_t neighbor;
route_info_t info;
} routing_table_entry;
inline void routeInfoInit(route_info_t *ri) {
ri->parent = INVALID_ADDR;
ri->etx = 0;
ri->haveHeard = 0;
ri->congested = FALSE;
/* senzip */
ri->hopDepth = 255;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | kasetsart/tos/platforms/iwing-mrf/hardware.h | <reponame>tinyos-io/tinyos-3.x-contrib<gh_stars>1-10
#ifndef _H_hardware_h
#define _H_hardware_h
#include "atm328hardware.h"
#endif // _H_hardware_h
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/support/sdk/c/blip/interface/queue.c | <gh_stars>1-10
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "queue.h"
int queue_init(struct blocking_queue *q) {
pthread_mutex_init(&q->mut, NULL);
pthread_cond_init(&q->cond, NULL);
q->head = NULL;
}
int queue_push(struct blocking_queue *q, void *data) {
struct queue_entry *new = (struct queue_entry *)malloc(sizeof(struct queue_entry));
if (!new) return -1;
pthread_mutex_lock(&q->mut);
new->q_data = data;
if (!q->tail) {
q->head = q->tail = new;
new->q_next = NULL;
} else {
new->q_next = NULL;
q->tail->q_next = new;
q->tail = new;
}
pthread_cond_broadcast(&q->cond);
pthread_mutex_unlock(&q->mut);
return 0;
}
/* blocks until there's something to pop */
void *queue_pop(struct blocking_queue *q) {
void *rv;
struct queue_entry *extra;
pthread_mutex_lock(&q->mut);
while (q->head == NULL) {
pthread_cond_wait(&q->cond, &q->mut);
}
extra = q->head;
q->head = extra->q_next;
if (!q->head) q->tail = NULL;
rv = extra->q_data;
free(extra);
pthread_mutex_unlock(&q->mut);
return rv;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.