## Formula evaluation with python

I've been working on an Internet of Things platform with some principles in mind:

- Simple (i.e. 'dumb') devices
- Powerful processing in the backend
- Flexibility in value calculation

To achieve the first goal, the physical devices (nodes, sensors, whatever you call them) will be uploading an array of values which will have to be processed by a server.

For example, our node will be sending a reading for the battery and a temperature sensor, packed in an array of 16-bit values, with the following sequence:

`array[0]`

: Battery`array[1]`

: Temperature

Since these values are 16-bit integers, we need to transform them to a meaningful representations. For example, the real temperature (in degrees Celcius) is calculated like this:

```
temp_celcius = (temp_read - 5500) / 100
```

A simple and generic way to do define this transformation would be defining string formulas and using an evaluation module, such as python's `parser`

module:

```
x = arr[1]
formula_temp = "(x - 5500) / 100"
code = parser.expr(formula_temp).compile()
print eval(code)
```

But what if we need to combine multiple array values into a single calculation? I figured that a JSON-defined reading would be a good way to do this. So, let's say we have a 32-bit value divided in two different places:

`array[2]`

: Higher part of counter (16-bit)`array[3]`

: Lower part of counter (16-bit)

We can define a formula that combines both:

```
formula = {'2': "x << 16", '3': "x"}
```

and then add both entries:

```
result_arr = []
for key, value in formula:
# Get the value in the array
x = arr[int(key)]
# Parse the formula contained in the JSON
code = parser.expr(value).compile()
# Add the result to the list of results
result_arr = result_arr + [eval(code)]
# Add all results
result = sum(result_arr)
```

there, we have a simple yet generic system to combine readings into meaningful values using any formula that we want.