@jgmdavies
Hi, I know you posted this topic a really long time ago but if you ever see this message, I would really appreciate you helping me. I am currently trying to do the same thing, sending/posting datas to ThingSpeak from a Pycom device using WiFi or any connection I can. However, I am facing many issues and have no idea how to make this works. I just read you managed to do it, could you please help me out with it ?
update data to thingspeak
Re: update data to thingspeak
Hi Alex,
I'm not active in this area right now, but I can pass you the Python 3.4 source as it was (below), and hope it's of some use. Use it any way you like, including in commercial products!
Multiple health warnings - the libraries I used may well have changed, etc.
I see it uses my 'WiPyFloat.py', also included below, but I'd recommend that you don't use that initially, for simplicity - perhaps your data is integer-only anyway?
Best wishes,
Jim
ts1A.py
WiPyFloat.py
I'm not active in this area right now, but I can pass you the Python 3.4 source as it was (below), and hope it's of some use. Use it any way you like, including in commercial products!
Multiple health warnings - the libraries I used may well have changed, etc.
I see it uses my 'WiPyFloat.py', also included below, but I'd recommend that you don't use that initially, for simplicity - perhaps your data is integer-only anyway?
Best wishes,
Jim
ts1A.py
Code: Select all
# ts1A.py
import os
import urequests
import time
import gc
import array
from WiPyFloat import Float
thingspeak_apikey = "YOUR_WRITE_KEY"
thingspeak_apikey_channel_126 = "YOUR_WRITE_API_KEY" # Write API key for channel 126
thingspeak_url = "https://api.thingspeak.com/update"
thingspeak_channel = 126
thingspeak_field = 1
def get_temp(city):
print("get_temp: " + city)
print("mem_free = {}".format(gc.mem_free()))
temp = 1234
try:
url = "http://temp.fkainka.de/?city=" + city
resp = urequests.get(url)
if (resp.status_code != 200):
print("Bad response from GET to: " + url + ", status code " + str(resp.status_code) + " (" + resp.reason + ")")
return None
content = resp.text
print(content)
index = content.find("Temp: ")
if (index < 0):
print("No temperature found in response from: " + url)
return None
index += 6
index2 = content.find(" ", index)
if (index < 0):
print("No temperature found in response from: " + url)
return None
s = content[index:index2]
temp = Float(s)
except Exception as e:
print("get_temperature: Failed to get temperature: " + url)
print(repr(e))
return None
return temp
def retrieve(chan):
import ujson
url = "https://api.thingspeak.com/channels/126/feeds.json?start=2014-01-28%2004:00:00&results=2"
s = '{"channel":{"id":126,"name":"Channel 126","description":"Public Channel 1 for Jim Davies.","latitude":"0.0","longitude":"0.0","field1":"Temperature","field2":"Humidity","created_at":"2011-02-21T19:28:15Z","updated_at":"2016-09-05T13:36:58Z","last_entry_id":1096},"feeds":[{"created_at":"2016-09-05T13:26:23Z","entry_id":1095,"field1":null,"field2":"50"},{"created_at":"2016-09-05T13:36:58Z","entry_id":1096,"field1":"70","field2":null}]}'
return ujson.loads(s)
def update(chan, field_num, value):
# Update a ThingSpeak channel feed.
try:
url = "http://api.thingspeak.com/update"
urlencoded = b"api_key=YOUR_WRITE_API_KEY&field" + str(field_num) + "=" + str(value)
headers = {"Content-Type": "application/x-www-form-urlencoded"}
resp = urequests.post(url, data=urlencoded, headers=headers)
if (resp.status_code == 200):
print("Response from POST to: " + url + ", status code " + str(resp.status_code))
print(resp.content)
else:
print("Bad response from POST to: " + url + ", status code " + str(resp.status_code) + " (" + resp.reason.decode() + ")")
return False
except Exception as e:
print("update: Failed to update channel: " + url)
print(repr(e))
return False
return True
def test1():
print("ts1A.test1")
print(os.uname().machine)
print(os.uname().version)
error_count = 0
while True:
temp = get_temp("brighton")
if temp:
print("Temp: ", temp)
ok = update(thingspeak_channel, thingspeak_field, temp.str())
else:
ok = False
if ok:
error_count = 0
else:
error_count += 1
if (error_count >= 4):
print("Too many consecutive errors")
break
time.sleep(20)
return True
Code: Select all
# WiPyFloat.py
# Last modified: 27 Aug 2016
# J.G.Davies, Jacobus Systems Ltd., Brighton & Hove, UK.
# This code is hereby released as Public Domain. I would appreciate an acknowledgement if you find it useful.
class Float():
mantissa = 0
exponent = 0
def __init__(self, f=None):
if f:
if (type(f).__name__ == "Float"):
self.mantissa = f.mantissa
self.exponent = f.exponent
elif (type(f).__name__ == "int"):
self.mantissa = int(f)
self.exponent = 0
elif (type(f).__name__ == "str"):
self.load(str(f))
self.normalise()
return
# Operator overloads.
def __abs__(self):
result = Float(self)
result.mantissa = abs(result.mantissa)
return result
def __add__(self, other):
return Float.add(self, other)
def __eq__(self, other):
self.normalise()
other.normalise()
return (self.mantissa == other.mantissa) and (self.exponent == other.exponent)
def __mul__(self, other):
return Float.multiply(self, other)
def __neg__(self):
result = Float(self)
result.mantissa = -result.mantissa
return result
def __pos__(self):
return Float(self)
def __str__(self):
return self.str()
def __sub__(self, other):
return Float.subtract(self, other)
def __truediv__(self, other):
return Float.divide(self, other)
# Static methods.
@staticmethod
def add(f1, f2):
# Return a new Float holding (f1 + f2).
result = Float(f1)
result.add_float(f2)
return result
@staticmethod
def divide(f1, f2):
# Return a new Float holding (f1 / f2).
result = Float(f1)
result.divide_float(f2)
return result
@staticmethod
def multiply(f1, f2):
# Return a new Float holding (f1 * f2).
result = Float(f1)
result.multiply_float(f2)
return result
@staticmethod
def subtract(f1, f2):
# Return a new Float holding (f1 - f2).
result = Float(f1)
result.subtract_float(f2)
return result
# Methods.
def add_float(self, f, add=True):
# Add Float 'f' to this Float.
# Align the exponents.
self_mantissa = self.mantissa
self_exponent = self.exponent
f_mantissa = f.mantissa
f_exponent = f.exponent
if (f_exponent < self_exponent):
shift = self_exponent - f_exponent
self_mantissa *= 10 ** shift
self_exponent -= shift
elif (f_exponent > self_exponent):
shift = f_exponent - self_exponent
f_mantissa *= 10 ** shift
f_exponent -= shift
if add:
self.mantissa = self_mantissa + f_mantissa
else:
self.mantissa = self_mantissa - f_mantissa
self.exponent = self_exponent
self.normalise()
return self
def debug(self):
s = "Float: {0}, {1}".format(self.mantissa, self.exponent)
return s
def divide_float(self, f):
# Divide this Float by 'f'.
self.mantissa *= 100000000
self.exponent -= 8
self.mantissa //= f.mantissa
self.exponent -= f.exponent
self.normalise()
return self
def int(self):
result = 0
return result
def load(self, s):
s = s.strip().lower()
pos = True
if (s[0] == "+"):
s = s[1:]
elif (s[0] == "-"):
s = s[1:]
pos = False
if "e" in s:
return self.load_scientific(s, pos)
if "." in s:
whole, decimal = s.split(".")
if not decimal:
# There is no decimal part.
# TODO: if 'whole' ends in zeros, could scale the number and set self.exponent.
# This would help keep 'mantissa' a simple 31-bit int on the WiPy.
self.mantissa = int(whole)
if not pos: self.mantissa = -self.mantissa
self.exponent = 0
self.normalise()
return True
# There is a decimal part.
if whole and (int(whole) == 0):
whole = None
if not whole:
# There is no whole part.
value, nleading = self.parse_decimal(decimal)
if value:
self.mantissa = int(value)
if not pos: self.mantissa = -self.mantissa
self.exponent = -nleading - len(value)
self.normalise()
else:
self.mantissa = 0
self.exponent = 0
return True
# There is a whole part and a decimal part.
whole = whole.lstrip("0")
decimal = decimal.rstrip('0')
self.mantissa = int(whole + decimal)
if not pos: self.mantissa = -self.mantissa
self.exponent = -len(str(decimal))
self.normalise()
else:
# TODO: if 'whole' ends in zeros, could scale the number and set self.exponent.
# This would help keep 'mantissa' a simple 31-bit int on the WiPy.
self.mantissa = int(s)
if not pos: self.mantissa = -self.mantissa
self.exponent = 0
self.normalise()
return True
def multiply_float(self, f):
# Multiply this Float by 'f'.
self.mantissa *= f.mantissa
self.exponent += f.exponent
self.normalise()
return self
def normalise(self):
# Normalise where possible.
if (self.mantissa != 0):
s = str(self.mantissa)
stripped = s.rstrip("0")
diff = len(s) - len(stripped)
if (diff > 0):
self.mantissa = int(stripped)
self.exponent += diff
return True
def str(self, format="F"):
if ("E" in format):
return self.str_scientific()
# Use format "F".
pos = (self.mantissa >= 0)
result = str(abs(self.mantissa))
if (self.exponent > 0):
result += "0" * self.exponent
elif (self.exponent < 0):
if (-self.exponent < len(result)):
cut = len(result) + self.exponent
result = result[:cut] + "." + result[cut:]
else:
n_zeros = -self.exponent - len(result)
result = "0." + ("0" * n_zeros) + result
if not pos: result = "-" + result
return result
def subtract_float(self, f):
# Subtract Float 'f' from this Float.
return self.add_float(f, False)
# Helper methods.
def load_scientific(self, s, pos):
mant, exp = s.split("e")
self.load(mant)
self.exponent += int(exp)
self.normalise()
return False
def parse_decimal(self, s):
nleading = 0
for c in s:
if (c != "0"): break
nleading += 1
if (nleading == 0):
value = s
else:
value = s[nleading:]
return value, nleading
def str_scientific(self):
pos = (self.mantissa >= 0)
result = str(abs(self.mantissa))
len_mantissa = len(result)
if (len(result) > 1):
result = result[:1] + "." + result[1:]
result = result.rstrip("0")
result = result.rstrip(".")
result += "e" + str(self.exponent + len_mantissa - 1)
if not pos: result = "-" + result
return result
if (__name__ == "__main__" ):
import Float_tests