0

I have been having trouble with updating this global variable that is an array of strings. This rfDataArray is supposed to be updated as the rf data is coming in from another device. Now, when I have tested this without sending anything over to the cloud servers, it works (the rfDataArray gets updated as frequently as the data is being sent) however as soon as I start sending the data, the rfDataArray array seems to be stuck at the initial array and does not get updated ever again...

import httplib, urllib
import time, sys
import serial

key = 'MY_API_KEY'
rfDataArray = []
rfWaterLevelVal = 0

ser = serial.Serial('/dev/ttyUSB0',9600)

def rfWaterLevel():
    global rfWaterLevelVal
    global rfDataArray

    rfDataArray = ser.readline().strip().split()
    print 'incoming: %s' %rfDataArray
    if len(rfDataArray) == 5:
        rfWaterLevelVal = float(rfDataArray[4])
        print 'RFWater Level1: %.3f cm' % (rfWaterLevelVal)


def sendRFWaterlevel():
    params = urllib.urlencode({'field1':rfWaterLevelVal, 'key':key})
    headers = {"Content-type": "application/x-www-form-urlencoded",
               "Accept": "text/plain"}
    conn = httplib.HTTPConnection("api.thingspeak.com:80", timeout = 5)
    conn.request("POST", "/update", params, headers)
    print 'RFWater Level2: %.3f cm' % (rfWaterLevelVal)
    response = conn.getresponse()
    print response.status, response.reason
    data = response.read()
    conn.close()

while True:
    try:
        rfWaterLevel()
        time.sleep(1)
        sendRFWaterlevel()
        time.sleep(3)
    except KeyboardInterrupt:
        print "caught keyboard interrupt"
        sys.exit()

I need to update therfDataArray variable (so the rfWaterlevelVal is updated to send over to the cloud servers).

martineau
  • 119,623
  • 25
  • 170
  • 301
Verglas
  • 79
  • 2
  • 10

1 Answers1

0

You are running into a race condition. The array is trying to store values before the cloud can send it back. You need to do the operations asynchronously. One solution is to use the callback methods from Python multithreading. Alternatively, you could use some 'locking' mechanism and not execute the rest of the program till you get a response from the cloud.

rt88
  • 43
  • 5
  • Could you possibly give me pointers to how to apply both of those potential solutions? – Verglas Jul 22 '16 at 01:22
  • [Here is a simple Stack Overflow Solution](http://stackoverflow.com/questions/1239035/asynchronous-method-call-in-python) for asynchronous calls. [Here] is python documentation for Synchronous calls (https://docs.python.org/3/library/asyncio-sync.html) – rt88 Jul 22 '16 at 01:28