def two(id_channel, api_key_channel, id_sensor, measure, data_alarm, data_error): global state_fuente_2 channel = thingspeak.Channel(id=id_channel, api_key=api_key_channel) if data_error == 1: print('Error de lectura') else: if id_sensor == 1: if data_alarm == 1: bot.send_message( chat_id='1083405023', text="Fuente 2 con valores de pH fuera de rango") state_fuente_2 = 0 channel.update({'field1': measure}) else: channel.update({'field1': measure}) state_fuente_2 = 1 elif id_sensor == 2: if data_alarm == 1: bot.send_message( chat_id='1083405023', text="Fuente 2 con valores de turbidez fuera de rango") state_fuente_2 = 0 channel.update({'field2': measure}) else: channel.update({'field2': measure}) state_fuente_2 = 1
def reloadConfigs(): global fanPort global minFanUpTime global refreshRate global maxTemp global minTemp global channel_id global write_key global tskrefresh global channel global isRelay global onValue global offValue global useSocCmd lastFanPort = fanPort (fanPort,minFanUpTime,refreshRate,maxTemp,minTemp,channel_id,write_key,tskrefresh,isRelay,useSocCmd) = configs.loadConfig() if(channel_id != -1): channel = thingspeak.Channel(id=channel_id,write_key=write_key) if(isRelay): onValue = 0 offValue = 1 else: onValue = 1 offValue = 0 GPIO.cleanup(lastFanPort) setGPIO()
def main(): """Run the code for thingspeak""" args = docopt(__doc__, version=ts.__version__) args = parse_json_config(args) log_level = logging.INFO # default if args['--verbose']: log_level = logging.DEBUG elif args['--quiet']: log_level = logging.ERROR logging.basicConfig( level=log_level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') log = logging.getLogger('thingspeak.main') log.debug(args) # Create channel class ch = ts.Channel( args['<channel>'], api_key=args['--api-key'], write_key=args['--write-key'], fmt=args['-f'], ) opts = dict() # Act on channel if args['<field>']: data = {k: v for k, v in zip(args['<field>'], args['<value>'])} print(ch.update(data)) if args['--results'] is not None: opts['results'] = args['--results'] results = ch.get(opts) if args['-f'] == 'json': print(json.dumps(json.loads(results), sort_keys=True, indent=2)) else: print(results) else: print(ch.view())
def write_to_db(obj): # holen der daten aus dem String text = json.loads(obj['text']) data = '{"html": "Die Daten Temperatur: ' + str(text['Temperature']) + ' °C und Luftfeuchtigkeit: ' \ + str(text['Humidity']) + '% wurden übermittlet", "roomId": "'+chatroomId+'"}' channel_id = 496768 write_key = "PZVVZFO8R5YJY0D7" read_key = "MO17791BOVEODHFV" channel = thingspeak.Channel(id=channel_id, write_key=write_key, api_key=read_key) tsresponse = channel.update({ 'field1': text['Temperature'], 'field2': text['Humidity'] }) read = channel.get({}) print("Read: ", read) print(data) print(url + "/messages" + " " + data + " " + json.dumps(headers)) iswritten = requests.post(url + "/messages", data=data, headers=headers) if iswritten.status_code != 200: print("Fehler beim Update Benachrichtigung senden " + iswritten.status_code + iswritten.text)
def get_channels(device_list): return { string.ascii_lowercase[idx]: { 'primary': thingspeak.Channel( id=device['THINGSPEAK_PRIMARY_ID'], api_key=device['THINGSPEAK_PRIMARY_ID_READ_KEY'], ), 'secondary': thingspeak.Channel( id=device['THINGSPEAK_SECONDARY_ID'], api_key=device['THINGSPEAK_SECONDARY_ID_READ_KEY'], ) } for idx, device in enumerate(device_list) }
def download_pa(): #TODO desperately needs to be async for cid, key in pairs: channel_id = cid read_key = key channel = thingspeak.Channel(id=channel_id, api_key=read_key) #prep columns for dataframe cols = json.loads(channel.get( {'results': '1'}))['channel'] # get the json for channel columns cols = [(key, value) for key, value in cols.items() if key.startswith('field')] # extract only field values cols = [unit for field, unit in cols] cols = [col + f'_{channel_id}' for col in cols] cols.insert(0, 'datetime') df = pd.DataFrame(columns=cols) for start, end in pairwise(dates): df = df.append(get_block(start, end)) # ['datetime', 'PM1.0 (ATM)_{channel_id}', 'PM2.5 (ATM)_{channel_id}', # 'PM10.0 (ATM)_248887', 'Mem_248887', # 'Unused_248887', 'PM2.5 (CF=1)_248887'] # # df = df.drop(columns = [f'Uptime_{channel_id}', # # f'RSSI_{channel_id}', # # f'Temperature_{channel_id}', # # f'Humidity_{channel_id}' # # ]) df.to_csv(f'data/purple_air/{channel_id}.csv') print(f'Channel: {channel_id} processed')
def get_channels(self, data): return { device: { 'primary': thingspeak.Channel( id=data[f'primary_id_{device}'], api_key=data[f'primary_key_{device}'], ), 'secondary': thingspeak.Channel( id=data[f'secondary_id_{device}'], api_key=data[f'secondary_key_{device}'], ) } for device in ('a', 'b') }
def main(): """Run the code for thingspeak""" args = docopt(__doc__, version=pkg_resources.get_distribution("thingspeak").version) args = parse_json_config(args) log_level = logging.INFO # default if args["--verbose"]: log_level = logging.DEBUG elif args["--quiet"]: log_level = logging.ERROR logging.basicConfig( level=log_level, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) log = logging.getLogger("thingspeak.main") log.debug(args) # Create channel class ch = ts.Channel(args["<channel>"], api_key=args["--api-key"], fmt=args["-f"]) opts = dict() # Act on channel if args["<field>"]: data = {k: v for k, v in zip(args["<field>"], args["<value>"])} print(ch.update(data)) if args["--results"] is not None: opts["results"] = args["--results"] results = ch.get(opts) if args["-f"] == "json": print(json.dumps(json.loads(results), sort_keys=True, indent=2)) else: print(results) else: print(ch.view())
def PA_sensor_pull(label): """ Get one full row of data for a single Purple Air sensor. args: dictionary key, string (e.g. 'Denver') output: string, SQL command to add one row of data to PostgreSQL database """ sensor_id = master_sensor[label]['id_primary'] final_row = [sensor_id] for key in key_list: channel_id = master_sensor[label][key[0]] read_key = master_sensor[label][key[1]] channel = thingspeak.Channel(id=channel_id, api_key=read_key) try: f_ = list( json.loads( channel.get(options={'results': 1}))['feeds'][0].values()) final_row.extend(key[2](f_)) except: pass psql_input = "INSERT INTO sensor_data (sensor_id, created_on, entry_id, A_PM1_ATM, A_PM25_ATM, A_PM10_ATM, temp, humidity, A_PM25_1,\ A_PM1_1, A_PM10_1,B_PM1_ATM, B_PM25_ATM, B_PM10_ATM, B_PM25_1,B_PM1_1, B_PM10_1) VALUES " + str( tuple(final_row)) + ";" return (psql_input)
def __init__(self, config, data): self.logging = logging.getLogger("thingspeak") self.config = config self.data = data self.thingspeak = thingspeak.Channel( self.config.thingspeak.channelid, api_key=self.config.thingspeak.writekey, timeout=self.config.thingspeak.timeout)
def get_average(): connect = thingspeak.Channel(id=channel_id, write_key=write_key, api_key=read_key) temp = connect.get({"average": "daily"}) data = json.loads(temp)['feeds'][0] return data
def status(bot, update): user = update.message.from_user logger.info("%s(%s) wants the status" % (user.first_name, user.id)) channel_esp8266 = thingspeak.Channel(id=ESP8266_CHANNEL_ID, api_key=ESP8266_READ_KEY) dict = json.loads(channel_esp8266.get_field_last(field='field1')) created_at = dict['created_at'] local = pytz.timezone('Asia/Seoul') utc_dt = datetime.datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%SZ") created_at = local.localize(utc_dt, is_dst=None) pm1_0 = dict['field1'] dict = json.loads(channel_esp8266.get_field_last(field='field2')) pm2_5 = dict['field2'] dict = json.loads(channel_esp8266.get_field_last(field='field3')) pm10_0 = dict['field3'] dict = json.loads(channel_esp8266.get_field_last(field='field5')) temperature = dict['field5'] dict = json.loads(channel_esp8266.get_field_last(field='field6')) humidity = dict['field6'] channel_rp = thingspeak.Channel(id=RP_CHANNEL_ID, api_key=RP_READ_KEY) dict = json.loads(channel_rp.get_field_last(field='field1')) kodi_temp = dict['field1'] dict = json.loads(channel_rp.get_field_last(field='field2')) rp_temp = dict['field2'] update.message.reply_text("* 측정 시간 : " + str(created_at) + '\n' + "- PM1.0 : " + pm1_0 + " ㎍/m³" + '\n' + "- PM2.5 : " + pm2_5 + " ㎍/m³" + '\n' + "- PM10.0 : " + pm10_0 + " ㎍/m³" + '\n' + "- 온도 : " + str(float(temperature)) + " ℃" + '\n' + "- 습도 : " + str(float(humidity)) + " %" + '\n' + "- KODI CPU 온도 : " + kodi_temp + " ℃" + '\n' + "- Raspberry Pi CPU 온도 : " + rp_temp + " ℃")
def __init__(self, channelID, writeKey, readKey): ''' Constructor ''' self.channelID = channelID self.writeKey = writeKey self.readKey = readKey self.sensor = Adafruit_DHT.DHT22 self.pin = 27 self.channel = thingspeak.Channel(id=channelID, write_key=writeKey, api_key=readKey) humidity, temperature = Adafruit_DHT.read_retry(self.sensor, self.pin) self.lastTemp = temperature self.lastHumidity = humidity
def SendData(temp=0, humidity=0, light=0, moisture=0): try: ch = thingspeak.Channel(1, API_KEY) ch.update({ "field1": temp, "field2": humidity, "field5": light, "field6": moisture }) except Exception as e: print("ThingSpeak connection failed", e) #test program #SendData(32,50)
def __init__(self): self.tab_sensors = os.listdir(ds_dir) self.file_log = open(Log + os.sep + "ds_log", "w", buffering=10) self.file_log.write("\n" * 2 + "*" * 20 + " python version " + str(sys.version_info) + "\n") if SHOW_OPTIONS == "print": print(self.tab_sensors) for folder in self.tab_sensors: if not label in folder: continue file1 = open(ds_dir + folder + os.sep + file_with_data) line = file1.readline() while line: line = file1.readline() file1.close() self.ch1 = thingspeak.Channel(id=CHANNEL_ID, write_key=WRITE_KEY) self.loopToGatherData()
def get_plot_data(): ch = thingspeak.Channel(id=1285446, api_key='AR5QVQ499RV99VD7', fmt='json') data_from_thingspeak = ch.get({}) data_list_from_thingspeak = data_from_thingspeak.split(",") data_list_from_thingspeak = data_from_thingspeak.split(",") print(data_list_from_thingspeak) temp = [] hum = [] alt = [] pres = [] i = 12 while i < len(data_list_from_thingspeak): #print(data_list_from_thingspeak[i:][2:6]) for line in (data_list_from_thingspeak[i:][2:6]): data = line.split('"') data_entry = float(data[3]) field = data[1] if field == 'field1': temp.append(data_entry) if field == 'field2': hum.append(data_entry) if field == 'field3': alt.append(data_entry) if field == 'field4': pres.append(data_entry) i += 6 print(temp, '\n', hum, '\n', alt, '\n', pres) plt.plot(temp, label="Temperature") plt.plot(hum, label="Humidity") plt.plot(alt, label="Altitude") plt.plot(pres, label="Pressure") plt.xlabel('Data Entry') plt.ylabel('Data magnitude') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left', ncol=2, mode="expand", borderaxespad=0.) plt.show()
def export_data(): ch = thingspeak.Channel(id=1285446, api_key='AR5QVQ499RV99VD7', fmt='json') data_from_thingspeak = ch.get({}) data_list_from_thingspeak = data_from_thingspeak.split(",") data_list_from_thingspeak = data_from_thingspeak.split(",") print(data_list_from_thingspeak) temp = [] hum = [] alt = [] pres = [] mdData = { 'Temperature': [], 'Humidity': [], 'Altitude': [], 'Pressure': [] } i = 12 while i < len(data_list_from_thingspeak): #print(data_list_from_thingspeak[i:][2:6]) for line in (data_list_from_thingspeak[i:][2:6]): data = line.split('"') data_entry = float(data[3]) field = data[1] if field == 'field1': temp.append(data_entry) mdData['Temperature'].append(data_entry) if field == 'field2': hum.append(data_entry) mdData['Humidity'].append(data_entry) if field == 'field3': alt.append(data_entry) mdData['Altitude'].append(data_entry) if field == 'field4': pres.append(data_entry) mdData['Pressure'].append(data_entry) i += 6 my_dataFrame = pd.DataFrame.from_dict(mdData) my_dataFrame.to_csv('out.csv', index=False)
def sendData(url,key,DHT22_temp,DHT22_humidity,BME_temp,BME_press,DSM501_particulas): """ Send event to internet site """ values = {'field1' : DHT22_temp,'field2' : DHT22_humidity,'field3' : BME_temp,'field4' : BME_press,'field5' : DSM501_particulas} log = time.strftime("%d-%m-%Y,%H:%M:%S") + ", " log = log + "{:.2f}C".format(DHT22_temp) + ", " log = log + "{:.2f}%".format(DHT22_humidity) + ", " log = log + "{:.2f}C".format(BME_temp) + ", " log = log + "{:.2f}hPa".format(BME_press) + ", " log = log + "{:.2f}".format(DSM501_particulas) print (log) ch = thingspeak.Channel(788430, key, 'json',10,url) ch.update(values)
def get_temp(channel_id): d = shelve.open(database) minutes = time.strftime("%M", time.localtime()) if minutes == "59" or minutes == "29" or str(channel_id) not in d: temp_json = json.loads( thingspeak.Channel(channel_id).get_field_last('field1')) temp = float(temp_json['field1']) if not isinstance(temp, float): sys.stderr.write("Error getting value for sensor " + str(channel_id) + "\n") if channel_id in d: temp = d[str(channel_id)] else: d[str(channel_id)] = temp else: temp = d[str(channel_id)] d.close() if isinstance(temp, float): return int(round(temp))
def setup(hass, config): """Set up the Thingspeak environment.""" import thingspeak conf = config[DOMAIN] api_key = conf.get(CONF_API_KEY) channel_id = conf.get(CONF_ID) entity = conf.get(CONF_WHITELIST) try: channel = thingspeak.Channel(channel_id, write_key=api_key, timeout=TIMEOUT) channel.get() except RequestException: _LOGGER.error( "Error while accessing the ThingSpeak channel. " "Please check that the channel exists and your " "API key is correct" ) return False def thingspeak_listener(entity_id, old_state, new_state): """Listen for new events and send them to Thingspeak.""" if new_state is None or new_state.state in ( STATE_UNKNOWN, "", STATE_UNAVAILABLE, ): return try: if new_state.entity_id != entity: return _state = state_helper.state_as_number(new_state) except ValueError: return try: channel.update({"field1": _state}) except RequestException: _LOGGER.error("Error while sending value '%s' to Thingspeak", _state) event.track_state_change(hass, entity, thingspeak_listener) return True
import thingspeak import ast import urllib2 from time import sleep baseurl = 'https://api.thingspeak.com/update?api_key=AADJWQV7BQZ5Z7BQ&field3=0' TS = thingspeak.Channel(890371, "PW2FWC512E3ZHE4Z") while (True): gas = TS.get_field_last(1) flame = TS.get_field_last(2) gas = ast.literal_eval(gas) flame = ast.literal_eval(flame) if ((flame < 100) or (gas > 200)): a = 1 else: a = 0 print gas['field1'] print flame['field2'] f = urllib2.urlopen(baseurl + str(a)) f.read() f.close() sleep(12)
while GPIO.input(GPIO_ECHO) == 0: startTime = time.time() log("Waiting for response") # Receving signal time while GPIO.input(GPIO_ECHO) == 1: stopTime = time.time() log("Received signal") # Difference between start and end TimeElapsed = stopTime - startTime distance = (TimeElapsed * 34300) / 2 return distance if __name__ == '__main__': channel = thingspeak.Channel(id=args.channelId, write_key=args.writeKey, api_key=args.readKey) GPIO.output(7,GPIO.HIGH) try: while True: print("#########") blink(short=True, times=2) currentDistance = measureDistance() height = maximum_distance - currentDistance t = time.localtime() current_time = time.strftime("%d.%m.%Y %H:%M:%S", t) # we know that the tank hast to have a distance of more than 10cm if currentDistance > 10 and height > 0: print ("%s: Measured distance = %.1f cm" % (current_time, currentDistance)) try: log("Uploading data...") response = channel.update({'field1': height })
import time channel_id = 1049013 # PUT CHANNEL ID HERE write_key = 'B530FR63JBR4S3MN' # PUT YOUR WRITE KEY HERE read_key = 'BQE5HYPZ0YTXJULT' # PUT YOUR READ KEY HERE def thermometer(channel): try: #callableculate CPU temperature of Raspberry Pi in Degrees C temp = int(open('/sys/class/thermal/thermal_zone0/temp').read() ) / 1e3 # Get Raspberry Pi CPU temp params = channel.update({'field5': temp}) print(temp) #print response.status, response.reason time.sleep(1) read = channel.get({}) print(read) except: print("connection failed") if __name__ == "__main__": channel = thingspeak.Channel(id=channel_id, api_key=write_key) while True: thermometer(channel) time.sleep(15)
from time import sleep chan_id = 1154788 # Get API keys from file try: with open("api_write_key.txt", "r") as keyfile: write_key = keyfile.read().strip() with open("api_read_key.txt", "r") as keyfile: read_key = keyfile.read().strip() except FileNotFoundError as e: print("Could not open keyfiles.") exit(1) # Create channel object channel = thingspeak.Channel(chan_id, write_key=write_key, read_key=read_key) # Write data to channel while True: # Get temperature temp = 0.0 if os.path.isfile("/sys/class/thermal/thermal_zone0/temp"): with open("/sys/class/thermal/thermal_zone0/temp", 'r') as temp_file: temp = int(temp_file.read().strip()) / 1000 # Send to thingspeak entry = channel.write({"Temperature": temp}) print(entry) sleep(10)
def __init__(self): #self.channel = thingspeak.Channel(id=978849, api_key="QKLLG1O7HCUKWV66") self.channel = thingspeak.Channel(id=980414, api_key="B1E91134TN7P6PJM")
from time import sleep from message import * # Get API keys from file try: with open("api_write_key.txt", "r") as keyfile: write_key = keyfile.read().strip() with open("api_read_key.txt", "r") as keyfile: read_key = keyfile.read().strip() except FileNotFoundError as e: print("Could not open keyfiles.") exit(1) # Get ThingSpeak channel object channel = thingspeak.Channel(1222699, write_key=write_key, read_key=read_key) # Create server on channel server = transport.Server(channel, "control_server") clients = {} while (True): r, _, _ = select.select(list(clients.keys()) + [server], [], []) for c in r: if c is server: connection, address = server.accept(block=False) print(f"New connection from \"{address}\".\n") clients[connection] = [0, None] # Send door state update
import bluetooth # needed for bluetooth communication import thingspeak # needed for thingspeak import time #for delay bluetooth_addr = "00:14:03:05:59:8F" # The address from the HC-06 sensor bluetooth_port = 1 # Channel 1 for RFCOMM bluetoothSocket = bluetooth.BluetoothSocket (bluetooth.RFCOMM) bluetoothSocket.connect((bluetooth_addr,bluetooth_port)) #thingspeak information channel_id = 997565 # channel ID from your Thingspeak channel key = "45O0RZQ5E187G5D5" # obtain from Thingspeak url = 'https://api.thinkspeak.com/update' # default URL to update Thingspeak ts = thingspeak.Channel(channel_id, key, url) print("Attempting Data Retrieval") while 1: try: received_data = bluetoothSocket.recv(1024) temperature = int.from_bytes(received_data,byteorder='big') time.sleep(0.5) lux = int.from_bytes(received_data,byteorder='big') print("Data Retrieved") print("Current Temperature: %d" % temperature) print("Current Lux: %d" %lux) # thingspeak_field1 = {"field1": temperature} # ts.update(thingspeak_field1) # update temp value in thingspeak # thingspeak_field2 = {"field2": lux} # ts.update(thingspeak_field2) # update lux value in thingspeak # print("Thingspeak Updated")
def setup(self) -> None: '''Initiailze metadata and real data for a sensor; for detailed info see docs''' # Meta self.lat = self.data.get('Lat', None) self.lon = self.data.get('Lon', None) self.id = self.data.get('ID', None) self.name = self.data.get('Label', None) self.location_type = self.data[ 'DEVICE_LOCATIONTYPE'] if 'DEVICE_LOCATIONTYPE' in self.data else '' # Parse the location (slow, so must be manually enabled) if self.parse_location: self.get_location() # Data if 'PM2_5Value' in self.data: if self.data['PM2_5Value'] != None: self.current_pm2_5 = float(self.data['PM2_5Value']) else: self.current_pm2_5 = self.data['PM2_5Value'] else: self.current_pm2_5 = '' try: f_temp = float(self.data['temp_f']) if f_temp > 150 or f_temp < -100: self.current_temp_f = None self.current_temp_c = None else: self.current_temp_f = float(self.data['temp_f']) self.current_temp_c = (self.current_temp_f - 32) * (5 / 9) except TypeError: self.current_temp_f = None self.current_temp_c = None except ValueError: self.current_temp_f = None self.current_temp_c = None except KeyError: self.current_temp_f = None self.current_temp_c = None try: self.current_humidity = int(self.data['humidity']) / 100 except TypeError: self.current_humidity = None except ValueError: self.current_humidity = None except KeyError: self.current_humidity = None try: self.current_pressure = self.data['pressure'] except TypeError: self.current_pressure = None except ValueError: self.current_pressure = None except KeyError: self.current_pressure = None # Statistics stats = self.data.get('Stats', None) if stats: self.pm2_5stats = json.loads(self.data['Stats']) self.m10avg = self.pm2_5stats['v1'] self.m30avg = self.pm2_5stats['v2'] self.h1ravg = self.pm2_5stats['v3'] self.h6ravg = self.pm2_5stats['v4'] self.d1avg = self.pm2_5stats['v5'] self.w1avg = self.pm2_5stats['v6'] try: self.last_modified_stats = datetime.utcfromtimestamp( int(self.pm2_5stats['lastModified']) / 1000) except TypeError: self.last_modified_stats = None except ValueError: self.last_modified_stats = None except KeyError: self.last_modified_stats = None try: self.last2_modified = self.pm2_5stats[ 'timeSinceModified'] # MS since last update to stats except KeyError: self.last2_modified = None # Thingspeak IDs self.tp_a = self.data['THINGSPEAK_PRIMARY_ID'] self.tp_a_key = self.data['THINGSPEAK_PRIMARY_ID_READ_KEY'] self.tp_b = self.data['THINGSPEAK_SECONDARY_ID'] self.tp_b_key = self.data['THINGSPEAK_SECONDARY_ID_READ_KEY'] self.channel_a = thingspeak.Channel(id=self.tp_a, api_key=self.tp_a_key) self.channel_b = thingspeak.Channel(id=self.tp_b, api_key=self.tp_b_key) # Diagnostic self.last_seen = datetime.utcfromtimestamp(self.data['LastSeen']) self.model = self.data['Type'] if 'Type' in self.data else '' self.hidden = False if self.data['Hidden'] == 'false' else True self.flagged = True if 'Flag' in self.data and self.data[ 'Flag'] == 1 else False self.downgraded = True if 'A_H' in self.data and self.data[ 'A_H'] == 'true' else False self.age = int(self.data['AGE']) # Number of minutes old the data is
def sample_sensors(): ret = {} ret["temperature_c"] = scd.temperature if ret["temperature_c"]: ret["temperature_f"] = ret["temperature_c"] * 1.8 + 32 ret["co2"] = scd.CO2 ret["humidity"] = scd.relative_humidity return ret ################## ### THINGSPEAK ################## ch = thingspeak.Channel(config.CHANNEL, api_key=config.API_KEY) def post_thingspeak(sensor_reading, sentiment=None): if sentiment: print("Sentiment is %s" % sentiment) else: print("posting %s ppm" % sensor_reading["co2"]) data = {} if sensor_reading["co2"] and sensor_reading["co2"] > 0: data[1] = sensor_reading["co2"] if sensor_reading["temperature_c"]: data[2] = sensor_reading["temperature_c"] data[3] = sensor_reading["temperature_f"] if sensor_reading["humidity"]: data[4] = sensor_reading["humidity"]
device_folder = glob.glob(base_dir + '28*')[0] device_file = device_folder + '/w1_slave' def read_temp_raw(): f = open(device_file, 'r') lines = f.readlines() f.close() return lines def read_temp(): lines = read_temp_raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos + 2:] temp_c = float(temp_string) / 1000.0 return temp_c channel = thingspeak.Channel("<your-channel>", "<your-write-api-key>") temperature = read_temp() print("Temperature", temperature) data = {"field2": temperature} channel.update(data) print("Finished")