Calling IoTPy functions from your code

Many IoTPy applications have data sources, such as sensors, that generate data continuously, and we want such applications to run forever. You can, however, also execute an IoTPy function on a fixed set of data. You do so by calling the functions run() and recent_values() as shown next.

You can also integrate your code with IoTPy in multiple threads of a process, multiple processes or multiple computers in a distributed system.

recent_values()

For any stream s, recent_values(s) is a list of the most recent values of s. Associated with a stream s is a parameter, num_in_memory, which you can set. If the length of stream s is less than or equal to num_in_memory, then recent_values(s) returns the value of the entire stream. If, however, the length of s exceeds num_in_memory, then recent_values(s) returns the num_in_memory, most recent values of s.

For example, if num_in_memory is 3 and s has 5 elements [0, 1, 2, 3, 4] at some point in the computation then at that point recent_values(s) is [2, 3, 4]. If at a later point s has 6 elements [0, 1, 2, 3, 4, 5] then at that point recent_values(s) is [3, 4, 5]

Example

Let’s look at a simple function that creates an agent. The output stream elements are squares of their corresponding input stream values. The function modifies the parameter count so that count[1] is the number of positive elements in the input stream and count[0] is the number of non-positive elements.

@map_e
def f(v, count):
    if v > 0: count[1] += 1
    else: count[0] += 1
    return v*v

Let’s define a function g that operates on a list and calls function f to do so.

def g(count, input_list):
    x = Stream('x')
    y = Stream('y')
    f(in_stream=x, out_stream=y, count=count)
    x.extend(input_list)
    run()
    return recent_values(y)

Here is an example call to g:

y_values = g(count=[0,0], input_list=[1, -3, 2])

After the call count is [1, 2], and y_values is [1, 9, 4]