TinyOS event return type meaning - tinyos

So in TinyOS an interface is composed of commands and events. When a module uses an interface, it calls its commands and provides an implementation of its events (provides an event handler).
The sense of the return type of a command is clear, it is the same as that of any function/method in any programming language, but, the return type of an event results unclear to me.
Let's take an example:
interface Counter{
command int64_t getCounter(int64_t destinationId);
event int64_t counterSent(int64_t destinationId);
}
Let's define a module that provides the Counter interface.
module Provider{
provides interface Counter;
}
implementation {
int64_t counter;
counter = 75; //Random number
/**
Returns the value of the counter and signals an event that
someone with id equal to destinationId asked for the counter.
**/
command int64_t getCounter(int64_t destinationId){
int64_t signalReturnedValue;
signalReturnedValue = signal counterSent(destinationId);
return counter;
}
}
Now let's define two module which use this interface.
module EvenIDChecker{
uses interface Counter;
}
implementation{
/**
Returns 1 if the destinationId is even, 0 otherwise
**/
event int64_t counterSent(int64_t destinationId){
if(destinationId % 2 == 0){
return 1;
} else {
return 0;
}
}
}
Now let's define another module which uses the same interface but does the inverse of the EvenIDChecker module.
module OddIDChecker{
uses interface Counter;
}
implementation{
/**
Returns 1 if the destinationId is odd, 0 otherwise
**/
event int64_t counterSent(int64_t destinationId){
if(destinationId % 2 == 1){
return 1;
} else {
return 0;
}
}
}
In the end, what would be the final value of the var signalReturnedValue?

The value is unspecified or this code may even not compile.
In TinyOS, there's a concept of combine functions, which are of signature type f(type, type) and their purpose is to reasonably combine two values of the same type. For error_t there's such a function defined:
error_t ecombine(error_t e1, error_t e2) {
return (e1 == e2) ? e1 : FAIL;
}
Combine function is called automatically in a situation such as in your code snippet.
If you want to define a combine function in this example, you need to typedef the return type of the event. See 4.4.3 Combine Functions for more information.
Note that the situation is symmetric for commands. You can wire two implementations of an interface to a single uses declaration like this:
configuration ExampleC {
ExampleP.Counter -> Counter1;
ExampleP.Counter -> Counter2;
}
Assuming that Counter has a command that returns something, whenever ExampleP calls that command, two implementations are executed and two return values are combined.

Related

After I declare an object from a class, and try to set a variable to that object inly, why does it say that it does not declare a type?

I am writing code for a school project that will be used for a Chromebook charging station with security. The problem I am having now is when I am detecting if a Chromebook is actually in the slot after the user has been assigned one, I am using a rocker switch to simulate this but when I am declaring the pin to the rocker, the arduino verfier comes up with that
"'slot1' does not name a type".
Code is below:
//class
class Chromebook_slot {
public:
String Name = "";
String RFID_tag = "";
int rocker = 0;
boolean chromebook_in = false;
//class function to check if chromebook is in.
//if not, redirect already to reassigning so chromebook slot is entered as open and free.
void set_if_in()
{
int momen_1_state = digitalRead(momen_1);
int momen_2_state = digitalRead(momen_2);
// the button has been pushed down and the previous process has been completed
// eg. servos would have been reset if there was a previous user
if (momen_1_state == HIGH || momen_2_state == HIGH)
{
chromebook_in = digitalRead(this->rocker);
if (chromebook_in == 0)
{
re_assigning();
}
else
{
return;
}
}
}
};
//this is now outside the class..
//class declarations
Chromebook_slot slot1;
Chromebook_slot slot2;
//variables for rocker switches which will act for detecting chromebooks.
// in my final version, this will replaced by a photoresistor and laser.
slot1.rocker = 3;
slot2.rocker = 2;
Where the function re_assigning() is a separate function declared further in the code and just resets the slot as open for future use.
slot1.rocker = 3;
slot2.rocker = 2;
These are statements that cannot be at the top level of a C++ (or .ino) file. They need to be inside of a function. What's happening is the compiler is looking looking at the slot1 identifier through the lens of potential valid constructions. It sees an identifier, and about the only thing that could legally exist at this point in the code that starts with an identifier like that is some declaration, e.g. int a = 7;, or more abstractly some_type some_more_stuff. So it expects slot1 to be a type, which it isn't, hence the message.
If you want an assignment like those to happen early on in an Arduino program, the simplest thing you could do is put them in setup():
void setup() {
slot1.rocker = 3;
slot2.rocker = 2;
// ...
}
Or, you'd make these part of the Chromebook_slot's constructor, such that they could be given in slot1 and slot2's declaration:
class Chromebook_slot {
public:
Chromebook_slot(int rocker_init_value) {
rocker = rocker_init_value;
}
// ...
Or in a maybe less familiar but more proper form, using the constructor's initialization list:
class Chromebook_slot {
public:
Chromebook_slot(int rocker_init_value)
: rocker(rocker_init_value) {}
// ...
Once you have a constructor for Chromebook_slot, your variables can become:
Chromebook_slot slot1(3);
Chromebook_slot slot2(2);

How to create a QFuture with an immediately available value?

I have a function which returns QFuture object as a result of a QtConcurrent::run computation. However, there could be some conditions before running the concurrent method where I need to manually return a value-holding future from my function.
QFuture<bool> foo(const QString &bar)
{
if (bar.isEmpty()) {
return QFuture<bool>(false); // This does not work.
// Here I need to return from the function, but I don't know how to do it.
}
return QtConcurrent::run([=]() -> bool {
// Asynchronous computations...
});
}
How to manually create the QFuture object?
Or (more globally) how to properly return from such method?
When there's no data to return, things are easy - this should be the first thing to try anyway in modern C++:
return {};
Or, if you're targeting some obsolete platform (<Qt 5.6):
return QFuture<bool>();
That way you get an invalid future. There's no way to directly create a future that carries preset data, you'd have to use QFutureInterface for that:
// https://github.com/KubaO/stackoverflown/tree/master/questions/qfuture-immediate-50772976
#include <QtConcurrent>
template <typename T> QFuture<T> finishedFuture(const T &val) {
QFutureInterface<T> fi;
fi.reportFinished(&val);
return QFuture<T>(&fi);
}
QFuture<bool> foo(bool val, bool valid) {
if (!valid)
return {};
return finishedFuture(val);
}
int main() {
Q_ASSERT(foo(true, true));
Q_ASSERT(!foo(false, true));
Q_ASSERT(foo(false, false).isCanceled());
Q_ASSERT(foo(true, false).isCanceled());
}

How to make Flow understand dynamic code that uses lodash for runtime type-checking?

Flow's dynamic code example indicates that Flow can figure out runtime type-checking:
function foo(x) {
if (typeof x === 'string') {
return x.length; // flow is smart enough to see this is safe
} else {
return x;
}
}
var res = foo('Hello') + foo(42);
But in real life, typeof isn't good enough. I usually use lodash's type-checking functions (_.isFunction, _.isString etc), which handle a lot of edge cases.
The problem is, if we change the example to use lodash for the runtime type-checking, Flow no longer understands it:
function foo(x) {
if (_.isString(x)) {
return x.length; // warning: `length` property not found in Number
} else {
return x;
}
}
var res = foo('Hello') + foo(42);
I tried using iflow-lodash but it doesn't seem to make a difference here.
What's the best solution to make Flow understand code that uses lodash for runtime type-checking? I'm new to Flow btw.
This would depend on having predicate types in your lodash libdefs.
Predicate types have recently been added to Flow. Although they are still in an experimental state so I would recommend being careful about their usage for anything serious for now.
function isString(x): boolean %checks { // << declare that the method is a refinement
return typeof x === 'string';
}
function method(x: string | number): number {
if (isString(x)) { // << valid refinement
return x.charCodeAt(0); // << no errors
} else {
return x;
}
}
[try it out]
Note: This answer may quickly fall out of date in one of the next releases as this is a brand new feature. Check out Flow's changelog for the latest information.
The solution for now if possible is to use the built-in refinements.
function method(x: string | number): number {
if (typeof x === "string") { // << Inline the check
return x.charCodeAt(0);
} else {
return x;
}
}
The most obvious solution for this specific case is:
if (_.isString(x) && typeof x === 'string') {
In general, you might be able to overcome Flow errors with creative error suppression, like this:
if (_.isString(x)) {
// #ManuallyTyped
var xStr: string = x;
return xStr.length;
} else { ... }
Make sure to define // #ManuallyTyped as a custom suppress_comment in your flow config file for this to work. You might need an ugly regex for that, see flow docs.
It's been a while since I've last done this, but if I recall correctly Flow will assume that your xStr is a string, while the rest of type checking will work just fine.

How to return a std::vector<const T*> to python?

I have a c++11 function that returns a:
std::vector<const T*> f();
with T being a c++ class that I exposed to python with class_. All the T instances reside in static storage that will live throught the live of the python process.
I am trying to expose f as a python function
getAllTs()
that would return python objects wrappers around T. I chose T* to be the held type for class_.
I am converting std::vector to a python tuple, with this bad semi-generic function:
template <typename Cont>
struct stdcont_to_python_tuple
{
static PyObject* convert(const Cont& container)
{
boost::python::list lst;
for (const auto& elt: container)
lst.append(elt);
return boost::python::incref( boost::python::tuple(lst).ptr() );
}
static PyTypeObject const* get_pytype()
{
return &PyTuple_Type;
}
};
I couldn't construct the tuple directory from the container. Is that possible?
I need to display these Ts in a UI table, perform sorting, filtering.
The max number of T instances is 30000 odd. In c++11:
sizeof(T) = 24 bytes
In python3:
sys.getsizeof(t) = 72 bytes
What is the return policy I can use where def'ing getAllTs to minimize duplication, ie to have the least extras added by python?
Thanks
Exposing std::vector<const T*> to Python
The easiest way to expose std::vector<...> is to expose it as a boost::python::class_, and use the vector_indexing_suite to provide a Python sequence like interface.
std::vector<const spam*> get_spams() { ... }
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
// Expose `spam`
python::class_<spam, spam*>("Spam");
// Expose `std::vector<const spam*>`
python::class_<std::vector<const spam*>>("Spams")
.def(python::vector_indexing_suite<std::vector<const spam*>>())
;
python::def("get_spams", &get_spams);
}
However, using the type const spam* may not be as fruitful as one would hope. First, Python does not have the concept of const. Furthermore, when exposing the spam class as being held by spam*, the automatic to-python and from-python converter are for spam*, not const spam*. This may not be immediately apparent due to the indexing suite returning proxies during indexing, but it will become apparent when iterating, as the iterator's value will attempt to be converted to Python.
spams = example.get_spams()
# Access by index returns a proxy. It does not perform a
# spam-to-python conversion.
spams[0].perform()
# The iterator's value will be returned, requiring a
# spam-to-python conversion.
for spam in spams:
pass
To resolve this, one can register an explicit to-python conversion for const spam*. I would strongly consider re-examining if const spam* is necessary, or if exposing spam as being held by a different type would be easier (e.g. boost::shared_ptr with a null deleter). Regardless, here is a complete example demonstrating this functionality:
#include <iostream>
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
/// Mocks...
struct spam
{
spam() { std::cout << "spam() " << this << std::endl; }
~spam() { std::cout << "~spam() " << this << std::endl; }
void perform() { std::cout << "spam::perform() " << this << std::endl; }
};
namespace {
std::array<spam, 3> spams;
} // namespace
std::vector<const spam*> get_spams()
{
std::vector<const spam*> result;
for (auto& spam: spams)
{
result.push_back(&spam);
}
return result;
}
/// #brief Convert for converting `const spam*` to `Spam`.
struct const_spam_ptr_to_python
{
static PyObject* convert(const spam* ptr)
{
namespace python = boost::python;
python::object object(python::ptr(ptr));
return python::incref(object.ptr());
}
};
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
// Enable `const spam*` to `Spam` converter.
python::to_python_converter<const spam*, const_spam_ptr_to_python>();
// Expose `spam`.
python::class_<spam, spam*>("Spam", python::no_init)
.def("perform", &spam::perform)
;
// Expose `std::vector<const spam*>`.
python::class_<std::vector<const spam*>>("Spams")
.def(python::vector_indexing_suite<std::vector<const spam*>>())
;
python::def("get_spams", &get_spams);
}
Interactive usage:
>>> import example
spam() 0x7ffbec612218
spam() 0x7ffbec612219
spam() 0x7ffbec61221a
>>> spams = example.get_spams()
>>> for index, spam in enumerate(spams):
... spams[index].perform()
... spam.perform()
...
spam::perform() 0x7ffbec612218
spam::perform() 0x7ffbec612218
spam::perform() 0x7ffbec612219
spam::perform() 0x7ffbec612219
spam::perform() 0x7ffbec61221a
spam::perform() 0x7ffbec61221a
~spam() 0x7ffbec61221a
~spam() 0x7ffbec612219
~spam() 0x7ffbec612218
Construct Python tuple from C++ container
A boost::python::tuple can be constructed from a sequence. If a C++ object is provided, then it needs to be convertible to a Python type that implements the Python iterator protocol. For instance, in the above example, as std::vector<const spam*> is exposed and provides a sequence like interface via the vector_indexing_suite, one could write get_spams() as:
boost::python::tuple get_spams()
{
std::vector<const spam*> result;
for (auto& spam: spams)
{
result.push_back(&spam);
}
return boost::python::tuple(result);
}
Alternatively, one can use types and functions provided by the boost/python/iterator.hpp file to create Python iterators from C++ Containers or Iterators. The examples demonstrate exposing a std::pair of iterators, begin and end, to Python. As the std::pair will have a to-python conversion available, one could construct a boost::python::tuple from the std::pair.
Here is a compete example demonstrating this approach:
#include <boost/python.hpp>
/// #brief Returns a tuple, constructing it form a range.
template <typename Container>
boost::python::tuple container_to_tuple(Container& container)
{
namespace python = boost::python;
return python::tuple(std::make_pair(
container.begin(), container.end()));
}
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
// Expose an int range.
typedef std::vector<int>::iterator vector_int_iterator;
typedef std::pair<vector_int_iterator, vector_int_iterator> vector_int_range;
python::class_<vector_int_range>("IntRange")
.def("__iter__", python::range(
&vector_int_range::first, &vector_int_range::second))
;
// Return a tuple of ints.
python::def("get_ints", +[] {
std::vector<int> result;
result.push_back(21);
result.push_back(42);
return container_to_tuple(result);
});
}
Interactive usage:
>>> import example
>>> ints = example.get_ints()
>>> assert(isinstance(ints, tuple))
>>> assert(ints == (21, 42))
Memory Footprint
If the C++ object already exists, one can have the python::object reference it via a pointer, which will reduce duplicating some overall memory usage. However, there are no options to reduce the base footprint of instances for Boost.Python classes, which comes from new-style class, size for variable-length data, C++ object, vtable pointer, pointer to instance holder, and padding for instance holder alignment. If you need a smaller footprint, then consider using the Python/C API directly for type creation, and using Boost.Python for interacting with the objects.

Can I get some advice on JavaScript delegates?

I'm rusty with delegates and closures in JavaScript, and think I came across a situation where I'd like to try to use one or both.
I have a web app that behaves a lot like a forms app, with fields hitting a server to change data on every onBlur or onChange (depending on the form element). I use ASP.NET 3.5's Web Services and jQuery to do most of the work.
What you need to know for the example:
isBlocking() is a simple mechanism to form some functions to be synchronous (like a mutex)
isDirty(el) checks to make sure the value of the element actually changed before wasting a call to the server
Agent() returns a singleton instance of the WebService proxy class
getApplicationState() passes a base-64 encoded string to the web service. This string represents the state of the application -- the value of the element and the state are passed to a service that does some calculations. The onSuccess function of the web service call returns the new state, which the client processes and updates the entire screen.
waitForCallback() sets a flag that isBlocking() checks for the mutex
Here's an example of one of about 50 very similar functions:
function Field1_Changed(el) {
if (isBlocking()) return false;
if (isDirty(el)) {
Agent().Field1_Changed($j(el).val(), getApplicationState());
waitForCallback();
}
}
The big problem is that the Agent().Field_X_Changed methods can accept a different number of parameters, but it's usually just the value and the state. So, writing these functions gets repetitive. I have done this so far to try out using delegates:
function Field_Changed(el, updateFunction, checkForDirty) {
if (isBlocking()) return false;
var isDirty = true; // assume true
if (checkForDirty === true) {
isDirty = IsDirty(el);
}
if (isDirty) {
updateFunction(el);
waitForCallback();
}
}
function Field1_Changed(el) {
Field_Changed(el, function(el) {
Agent().Field1_Changed($j(el).val(), getTransactionState());
}, true);
}
This is ok, but sometimes I could have many parameters:
...
Agent().Field2_Changed($j(el).val(), index, count, getApplicationState());
....
What I'd ultimately like to do is make one-linen calls, something like this (notice no getTransactionState() calls -- I would like that automated somehow):
// Typical case: 1 value parameter
function Field1_Changed(el) {
Field_Changed(el, delegate(Agent().Field1_Changed, $j(el).val()), true);
}
// Rare case: multiple value parameters
function Field2_Changed(el, index, count) {
Field_Changed(el, delegate(Agent().Field1_Changed, $j(el).val(), index, count), true);
}
function Field_Changed(el, theDelegate, checkIsDirty) {
???
}
function delegate(method) {
/* create the change delegate */
???
}
Ok, my first question is: Is this all worth it? Is this harder to read but easier to maintain or the other way around? This is a pretty good undertaking, so I may end up putting a bounty on this one, but I'd appreciate any help you could offer. Thanks!
UPDATE
So, I've accepted an answer based on the fact that it pointed me in the right direction. I thought I'd come back and post my solution so that others who may just be starting out with delegates have something to model from. I'm also posting it to see if anybody wants to try an optimize it or make suggestions. Here's the common Field_Changed() method I came up with, with checkForDirty and omitState being optional parameters:
function Field_Changed(el, args, delegate, checkForDirty, omitState) {
if (isBlocking()) return false;
if (!$j.isArray(args) || args.length == 0) {
alert('The "args" parameter in Field_Changed() must be an array.');
return false;
}
checkForDirty = checkForDirty || true; // assume true if not passed
var isDirty = true; // assume true for updates that don't require this check
if (checkForDirty === true) {
isDirty = fieldIsDirty(el);
}
if (isDirty) {
omitState = omitState || false; // assume false if not passed
if (!omitState) {
var state = getTransactionState();
args.push(state);
}
delegate.apply(this, args);
waitForCallback();
}
}
It handles everything I need it to (check for dirty, applying the application state when I need it to, and forcing synchronous webservice calls. I use it like this:
function TransactionAmount_Changed(el) {
Field_Changed(el, [cleanDigits($j(el).val())], Agent().TransactionAmount_Changed, true);
}
cleanDigits strips out junk characters the user may have tried to type in. So, thanks to everyone, and happy coding!
OK, few things:
Delegates are extremely simple in javascript since functions are first class members.
Function.apply lets you call a function with an array of arguments.
So you can write it this way
function Field_Changed(delegate, args)
{
if (isBlocking()) return false;
if (isDirty(args[0])) { //args[0] is el
delegate.apply(this, args);
waitForCallback();
}
}
And call it as:
Field_Changed(Agent().Field2_Changed, [el, getApplicationState(), whatever...]);
I have been using the following utility function that I wrote a long time ago:
/**
* #classDescription This class contains different utility functions
*/
function Utils()
{}
/**
* This method returns a delegate function closure that will call
* targetMethod on targetObject with specified arguments and with
* arguments specified by the caller of this delegate
*
* #param {Object} targetObj - the object to call the method on
* #param {Object} targetMethod - the method to call on the object
* #param {Object} [arg1] - optional argument 1
* #param {Object} [arg2] - optional argument 2
* #param {Object} [arg3] - optional argument 3
*/
Utils.createDelegate = function( targetObj, targetMethod, arg1, arg2, arg3 )
{
// Create an array containing the arguments
var initArgs = new Array();
// Skip the first two arguments as they are the target object and method
for( var i = 2; i < arguments.length; ++i )
{
initArgs.push( arguments[i] );
}
// Return the closure
return function()
{
// Add the initial arguments of the delegate
var args = initArgs.slice(0);
// Add the actual arguments specified by the call to this list
for( var i = 0; i < arguments.length; ++i )
{
args.push( arguments[i] );
}
return targetMethod.apply( targetObj, args );
};
}
So, in your example, I would replace
function Field1_Changed(el) {
Field_Changed(el, delegate(Agent().Field1_Changed, $j(el).val()), true);
}
With something along the lines
function Field1_Changed(el) {
Field_Changed(el, Utils.createDelegate(Agent(), Agent().Field1_Changed, $j(el).val()), true);
}
Then, inside of Agent().FieldX_Changed I would manually call getApplicationState() (and encapsulate that logic into a generic method to process field changes that all of the Agent().FieldX_Changed methods would internally call).
Closures and delegates in JavaScript:
http://www.terrainformatica.com/2006/08/delegates-in-javascript/
http://www.terrainformatica.com/2006/08/delegates-in-javascript-now-with-parameters/

Resources