⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 manual.html

📁 tinyos中文手册,是根据tinyos系统自带手册翻译过来的,虽然质量不好,但是对英文不强的人还是有用的
💻 HTML
📖 第 1 页 / 共 4 页
字号:
  global id  if event.get_id() == id:    print "Printing motes 1-20"    for i in range(0, 20):      print motes[i]    # Reschedule to happen again in one minute    simcore.interp.interruptInFuture(event.getTime() + simtime.onemin, id)</PRE><P>This can get the job done, but is clunky, verbose and difficult.Changing the period from once a minute to twice a minute requires anew function. In order to just print out mote state every thirtyseconds, a user has to write a function, request a pause ID, registera handler, and schedule an event to go off.<P>The <TT>simutil</TT> package provides a convenience class,<TT>Periodic</TT> for exactly this reason:<P><PRE>from simutil import Periodicimport simtimedef time_handler(event):  print "Printing motes 1-20"  for i in range(0, 20):    print motes[i]p = Periodic(simtime.onemin, time_handler)</PRE><P>Because Python functions are first class values, we can use closuresto dynamically generate functions with the parameters a user needs.Thus telling Tython to print out a range of mote states periodicallycan be done with a single function call:<P><PRE>from simutil import Periodicimport simtimedef print_state(low_mote, high_mote, period):  def time_handler(event):    print "Printing motes ", low_mote, " to ", high_mote    for i in range(low_mote, high_mote):      print motes[i];  return Periodic(period, time_handler);p = print_state(3, 5, simtime.onemin);</PRE><P>In this example, <TT>print_state</TT> returns the newly allocated<TT>Periodic</TT> object instance, whose <TT>stop</TT> method can beused to stop the recurring action. Once <TT>print_state</TT> iscalled, the Tython environment will print out the state of motes<TT>low_mote</TT> to <TT>high_mote</TT>, every <TT>period</TT> ticks.<P>Closures can also be used for periodic commands to TOSSIM. Forexample, a test of a routing protocol may want to inject periodicbeacons from a PC to a mote over the UART:<P><PRE>from simutil import *def uart_beacon(mote, period, msg):  def sendMessage(event):    comm.sendUARTMessage(mote, 0, msg)  return Periodic(period, sendMessage)</PRE><P><H2><A NAME="sec:behavior_objects">Behavior Objects</A></H2><P>Using closures as described in the previous <ahref="sec:periodic_actions">section</a> allows scripts to startperiodic actions in a concise and simple manner. One use of this is toimplement mote behaviors. For example, to make a mote move in a randomwalk, all one needs is a handler that moves a mote a small randomstep, then schedule this event to go off periodically.<P>One problem that emerges is conflicting behaviors. For example, onecould call <TT>random_walk()</TT> to make a mote move randomly, andalso call <TT>move_to()</TT> to make it move towards a specificqdestination. By registering two event handlers, the script hasspecified two conflicting movement behaviors, which will interleaveand come into conflict.<P>A clean solution to solve this problem is through the use of a Pythonobject. The object has functions for each of the different behaviors,and stores state on what behavior a mote is currently following. Italso implements a singleton pattern to ensure that only one instanceof hte object is created.<P>From an abbreviated example adapted from the <TT>simutil</TT> package:<P><PRE>## MoteMover is a utility class that handles various movement patterns# for motes. #import simcoreimport simutilimport simtimeimport mathfrom net.tinyos.sim.event import InterruptEventfrom java.util import Random# there should be only a single instancemotemover = None;class MoteMover:  def __init__(self):    global motemover    if (motemover != None):      raise "Cannot instantiate MoteMover more than once"    self.rand = Random();      handlers = {}  rate = simtime.onesec  #  # Move the mote to the given x,y position, moving a distance of  # 'step' each time. Calls the arrivedCallback when it gets there.  #  def moveTo(self, mote, step, x, y, arrivedCallback = None, rate = -1):    moteID = mote.getID();    if rate == -1:      rate = int(self.rate)        if (self.handlers.has_key(moteID)):      raise IndexError("Mote ID %d already on the move" % moteID)    dx = x - mote.getXCoord();    dy = y - mote.getYCoord();    distance = mote.getDistance(x, y);    nsteps = distance / step;    xstep = dx / nsteps;    ystep = dy / nsteps;    def callback(pauseEvent):      distance = mote.getDistance(x, y);      if (distance < step):        mote.moveTo(x, y);        self.stop(mote); # clear handlers, cancel event, etc        if (arrivedCallback != None):          arrivedCallback(mote)      else:        mote.move(xstep, ystep);    periodic = simutil.Periodic(rate, callback);    self.handlers[moteID] = (periodic, 'move_to');  #  # Move the given mote in a random walk pattern, moving a distance of  # 'step' units on each time interval.  #  def randomWalk(self, mote, step, rate=-1):    moteID = mote.getID();        if rate == -1:      rate = self.rate          if (self.handlers.has_key(moteID)):      raise IndexError("Mote ID %d already on the move" % moteID)    def callback(pauseEvent):      x = self.rand.nextDouble() * step * 2.0 - step;      y = self.rand.nextDouble() * step * 2.0 - step;      simcore.motes[moteID].move(x, y)      # print "random_walk: move mote %d by (%d, %d)" % (moteID, x, y);          periodic = simutil.Periodic(rate, callback);    self.handlers[moteID] = (periodic, 'random_walk')</PRE><P>In this example, the class variable <TT>handlers</TT> is used to storethe notion of whether or not a particular mote is moving. Conflictingmovement patterns are therefore detected and an error is reported.Additional movement patterns can be easily added to the object as newfunctions that follow the same pattern to avoid conflict.<H2><A NAME="sec:mote_variables">Mote Frame Variables</A></H2><P>One of Tython's most powerful features is the ability to requestsnapshots of variables from the running TOSSIM simulation.Specifically, the <tt>Mote</tt> object (accessible through the<tt>motes</tt> list), implements four functions (<TT>getBytes()</TT>,<TT>getLong()</TT>, <TT>getInt()</TT>, and <TT>getShort()</TT>) thatallow you to request variable values from TOSSIM, returning them inthe appropriate type.<P>The string parameter to each of these functions is the variable's Cname. For nesC components, this takes the form of<tt>&lt;component_name&gt;$&lt;variable_name&gt;</tt> For example,this code fetches some variables from the TimerM component of mote 2:<P><PRE>tail = motes[2].getByte("TimerM$queue_tail")head = motes[2].getByte("TimerM$queue_head")print "head: ", head,  "tail: ", tail</PRE><P>The <TT>getBytes()</TT> function can be used to fetch entirestructures. Currently, the variable parameter does not supportaccessing structure fields, pointer traversals, or array elements.Therefore, while <TT>getBytes("TimerM$mTimerList")</TT> will returnall of the timer structures as an array of bytes,<BR><TT>getBytes("TimerM$mTimerList[1]")</TT> and<TT>getBytes("TimerM$mTimerList[1].ticks")</TT> do not work.<HR><H1><A NAME="sec:design">Appendix A: Design Ideology</A></H1><P>Tython is a new system that adds a powerful new tool to the sensornetwork developer's portfolio. Through both predefined scripts andinteractive console sessions, Tython aids the tasks of developing,testing, and evaluating a new algorithm or application. The corearchitecture is extensible, allowing developers to write new pythonmodules and <TT>SimDriver</TT> plugins to add new forms of interactionand manipulation.<P>The primary goal of Tython is to offer the sensor network developer asimulation environment with dynamic interactivity, enabling bothunattended simulation experiments, as well as interactive debugggingand simulation control. The confluence of these two goals informs themajor design decisions of our project, as well as the particularinterfaces exposed by the Tython commands and classes.<P>In some senses, the first order design question relates to the valueof a dynamic simulation environment. Indeed, TOSSIM alone is avaluable tool for aiding sensor network development, offering ascalable simulation of a network of sensor motes with a fairlyrealistic radio model and a rich debugging capability (gdb). YetTOSSIM alone essentially just simulates tossing a set of motes into afield and letting them go, assuming a constant radio topology. On theother hand, the real world is a dynamic place; objects and motes canmove, radio connectivitity changes, motes can fail. An important toolin the developer's toolbox, therefore, is the ability to simulatethese dynamic interactions and thereby engineer a program that cancope with these situations.<P>Rather than integrating dynamically controlled interfaces to TOSSIM,the simulator instead implements a network protocol that allowsinteractive applications to connect to and control a runningsimulation. This separation allows the TOSSIM code base to remaininsulated and relatively lean (maintaining performance capabilities),while more complicated calculations and interactivity can beimplemented in a separate process.<P>TinyViz was a tool that enables developers to dynamically manipulate asimulation. The protocol between TOSSIM and TinyViz enables the GUI tointroduce dynamics into a test application's execution. However, GUIelements do not address all the needs of a dynamic interaction. Ingeneral, a user's interaction with a GUI is non-deterministic, makingrepeated executions of a test case difficult if not impossible toreproduce. Furthermore, to run a set of experiments using manualmanipulation of the simulation state is an extremely cumbersome task,limiting the developer to a simple cursory exploration of thepotential interactivity parameter space.<P>The TinyViz plugin system is an available avenue to manipulate orvisualize the parameters of an application. The plugin API allows aJava object to be loaded into the TinyViz GUI environment and tointeract with the TOSSIM protocol. Through custom plugins, anapplication writer could fully express control over the dynamics of aparticular experiment. In point of fact, much of the core Tythonfunctionality is implemented using the TinyViz plugin system. However,writing custom plugins is an insufficient solution due not only to thecumbersome nature of writing experiments in a compiled language, butmore importantly that it does not enable interactive code execution.In addition, being able to run an unattended simulation is a valuableconvenience to developers.<P>Through a scripting environment, developers are able to controlexperiments through repeatable interactions. The Python and reflectedJava commands/objects expose the key control elements of thesimulation environment. These hooks can be used both in a controlledexperiment framework and through console interaction with a runningsimulation. The interative console session is both useful for dynamicdebugging and investigation of an experiment, but also as aprototyping arena for code that may become part of a longer experimentframework. The dynamic console functionality not only eases the burdenof writing simulation scripts, but also enables interactiveexperimentation with the simulation itself. A developer can pause asimulation at a given time, use the variable resolution features toprobe around (and potentially alter) the simulation state, thencontinue the simulation to observe the effects of the actions.<P><HR><H1><A NAME="sec:about">About this document..</A></H1><STRONG>Tython: Scripting TOSSIM</STRONG><P>This document was generated using the <AHREF="http://www.latex2html.org/"><STRONG>LaTeX</STRONG>2<tt>HTML</tt></A>translator Version 2002 (1.62)<P>Copyright &#169; 1993, 1994, 1995, 1996,<A HREF="http://cbl.leeds.ac.uk/nikos/personal.html">Nikos Drakos</A>, Computer Based Learning Unit, University of Leeds.<BR>Copyright &#169; 1997, 1998, 1999,<A HREF="http://www.maths.mq.edu.au/~ross/">Ross Moore</A>, Mathematics Department, Macquarie University, Sydney.<P><P>This document is based on an initial translation run by Michael Demmeron January 30, 2004 as a conversion from the previous version of theTython manual. Since then, both formatting and content have beenheavily modified.</BODY></HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -