def post_var(device, temp, humidity, plant_height, light): try: url = "https://industrial.api.ubidots.com/" url = url + "api/v1.6/devices/" + device headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"} data = build_json("temperature", temp, "height", plant_height, "humidity", humidity, "light", light) if data is not None: print(data) req = requests.post(url=url, headers=headers, json=data) return req.json() else: pass except: pass
def send_data(): API_KEY = read_api_key() aws_url = 'https://m3q6ssas8g.execute-api.us-east-2.amazonaws.com/default/sls' headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'x-api-key': API_KEY } try: res = urequests.post(aws_url, json=washer_data, headers=headers) print(res.text) res.close() except: print("There was an exception, trying again") connect_open_wifi() send_data()
def sendData(keepalive, solarRaw): global errorcount try: status = urequests.post(post_url, data=post_data.format(keepalive, solarRaw)) print(status.status_code) status.close() errorcount = 0 except Exception as e: print("Error no. {}".format(errorcount), e) errorcount+=1 if errorcount > 4: machine.reset() else: net.disconnect() net.connect() wait_connect()
def call_home(reading, api_key, plant_id): url = "https://api.moistlywet.com/api/v1/plant/%s/moisture" % plant_id headers = { "moistly-wet-api-key": api_key, "content-type": "application/json" } data = {"moisture": reading} try: print(data) res = urequests.post(url, json=data, headers=headers) print(res.text) return res.json() except Exception as e: print(e) return {}
def post_event(name, data): try: url = "https://api.wia.io/v1/events" headers = {"Authorization": "Bearer " + DEVICE_SECRET_KEY, "Content-Type": "application/json"} json_data = {"name": name, "data": data} if json_data is not None: req = requests.post(url=url, headers=headers, json=json_data) if req.status_code is not 200: machine.reset() else: print(json_data) return req.json() else: pass except: pass
def postJSON(j, retries=0): if retries < 6: # Only retry the connection 5 times, otherwise, give up TODO: Don't give up silently! import urequests as requests wlan = network.WLAN(network.STA_IF) if wlan.isconnected(): # Check connection r = requests.post(url=postURL, json=j, headers={"Authorization": "Basic " + farmOSAuth}) # Send the psot request if (r.status_code == 201): # Check if the response is 201: Created - The correct reponse from FarmOS print("success") return True else: # Otherwise, retry postJSON(j, retries+1) else: do_connect() postJSON(j, retries+1) else: return False
def enviar_API(url, fecha, valor, sensor): """ esta funcion se encarga de enviar los datos a la API""" date = str(fecha[0]) + "-" + str(fecha[1]) + "-" + str( fecha[2]) + " " + str(fecha[3]) + ":" + str(fecha[4]) + ":" + str( fecha[5]) pyload = {"fecha": date, "valor": valor, "sensor": sensor} r = urequests.post(url, json=pyload, headers={ "Authorization": " Token 9a74a56ab171cacdee5654cfc2ebd126694e1bf0", "Content-Type": "application/json" }) print(r.content) print(r.status_code) r.close()
def post_things(batt, temp, humid): try: things_url = "https://api.thingspeak.com/update?api_key=7KLOY6PYHRDO4U8W" my_url = things_url + "&field1=" + str(batt) + "&field2=" + str( temp) + "&field3=" + str(humid) print(my_url) #r = requests.post(my_url,timeout=REQUESTS_TIMEOUT) r = requests.post(my_url) except Exception as e: print(e) #r.close() return "timeout" else: r.close() print('Status', r.status_code) return "posted"
def create(self, device_info: dict) -> str: r = requests.post( self._C8Y_HOST + "/inventory/managedObjects", headers={ 'Authorization': self._auth, 'Content-Type': 'application/vnd.com.nsn.cumulocity.managedObject+json', 'Accept': 'application/vnd.com.nsn.cumulocity.managedObject+json' }, json=device_info) if self.DEBUG: print("{}: {}".format(r.status_code, bytes.decode(r.content))) if r.status_code == 201: return r.json()["id"] r.raise_for_status()
def register(self, serial: str, id: str) -> bool: r = requests.post( self._C8Y_HOST + "/identity/globalIds/{}/externalIds".format(id), headers={ 'Authorization': self._auth, 'Content-Type': 'application/vnd.com.nsn.cumulocity.externalId+json', 'Accept': 'application/vnd.com.nsn.cumulocity.externalId+json' }, json={ "type": "c8y_Serial", "externalId": serial }) if self.DEBUG: print("{}: {}".format(r.status_code, bytes.decode(r.content))) return r.status_code == 201
def post(topic, value): try: data = build_json(topic, value) if data is not None: r = requests.post(url=(keys.url + keys.pub), headers=keys.headers, json=data) # include data as JSON object json_obj = r.json() r.close() return json_obj else: print("ERROR: JSON Empty. Nothing to post.") pass except: print("ERROR: Can't send data to Ubidots.") pass
def SendAWS(label, ID, seq, x1, x2, y1, y2, z1, z2): headers = {"Content-Type": "application/json; charset=UTF-8"} url = "http://3.87.68.197:8099/predict/post" request_data = { "label": label, "ID": ID, "seq": seq, "x1": x1, "x2": x2, "y1": y1, "y2": y2, "z1": z1, "z2": z2 } return urequests.post(url, data=json.dumps(request_data), headers=headers).text
def measurement(self, data: dict) -> Response: data["source"] = {'id': self._id} r = requests.post( self._C8Y_HOST + "/measurement/measurements", headers={ 'Authorization': self._auth, 'Content-Type': 'application/vnd.com.nsn.cumulocity.measurement+json', 'Accept': 'application/vnd.com.nsn.cumulocity.measurement+json' }, json=data) if self.DEBUG: print("{}: {}".format(r.status_code, bytes.decode(r.content))) if r.status_code == 201: return r.json() r.raise_for_status()
def read_messages(self): result = [] self.query_updates = { 'offset': self.message_offset, 'limit': 1, 'timeout': 30, 'allowed_updates': ['message']} try: update_messages = urequests.post(self.url + '/getUpdates', json=self.query_updates).json() if 'result' in update_messages: for item in update_messages['result']: if 'text' in item['message']: result.append(item) return result except: return None
def upload(self, hex_data): print("Uploading values to server:") payload = ujson.dumps({ "jsonrpc": "2.0", "method": "push_aidon_values", "params": { "meter_values": hex_data }, "id": self.inc_id() }) pprint(payload) self.connect() response = urequests.post(self._request_url, headers={'Content-Type': 'application/json'}, data=payload) response.close() print("Upload done!")
def push(self): import gc, urequests if not self._data: return gc.collect() data = "\n".join(self._data) print(data) try: res = urequests.post( "https://iotplotter.com/api/v2/feed/{0}.csv".format(self.feed_id), headers={"api-key": self.api_key}, data=data ) res.close() except: pass self._data = []
def submit_td(td): print("Uploading TD to directory. Please wait...") tries = 0 while tries < 1: try: tries += 1 r = urequests.post("{}/td".format(TD_DIRECTORY_ADDRESS), json=td) r.close() print ("Got response: ", r.status_code) if 200 <= r.status_code <= 299: print('TD uploaded!') return except Exception as e: print(e) if tries < 3: utime.sleep(1) print("Skipping TD upload ...")
def raw_send_to_influx(host, port, db, user, password, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, rssi, lqi): post = "http://{}:{}/write?db={}".format(host, port, db) if _DEBUG: print(b"SENDING TO: {}".format(post)) data = "data b0={_b0},b1={_b1},b2={_b2},b3={_b3},b4={_b4},b5={_b5},b6={_b6},b7={_b7},b8={_b8},b9={_b9},rssi={_rssi},lqi={_lqi}".format( _b0=b0, _b1=b1, _b2=b2, _b3=b3, _b4=b4, _b5=b5, _b6=b6, _b7=b7, _b8=b8, _b9=b9, _rssi=rssi, _lqi=lqi) if _DEBUG: print(b"POST_DATA: {}".format(data)) try: return (True, urequests.post(post, data=data)) except Exception as e: if e.args[0] == 103: machine.reset() else: return (False, b"ERROR sending RAW data to influx: {}".format(e))
def login(self): headers = {'content-type': 'application/json'} try: r = requests.post( url = "http://%s:%d/api/user/login"%(self.host, self.port), data = dumps({"email": self.email, "pass": self.password}), headers = headers ) print(r.json()["message"]) user = r.json() self.user = user return r.status_code == 200 except Exception as e: print_exception(e) self.user = None return False
def fttt(tim3): #Remember we are assuming u = 0, t = 1. Therefore my velocities would be equal to acceleration. #Therefore, instead of creating the vector I used my function and math here. global SessionID ifttt_data_send = { 'value1': str(SessionID), 'value2': str(mpu.acceleration()) + "|||" + str(mpu.__read_gyro()), 'value3': str(mpu.temperature()) } object_headers = {'Content-Type': 'application/json'} request = urequests.post(url, json=ifttt_data_send, headers=object_headers) if request is not None and request.status_code < 400: print('Webhook invoked') else: print('Webhook failed') SessionID = SessionID + 1 request.close()
def send_email_notification(): wlan = WLAN(mode=WLAN.STA) wlan.connect(ssid="Jordan Erifried's iPhone", auth=(WLAN.WPA2, "Jordan2002")) if not wlan.isconnected(): print('looking for network....') wlan.connect(ssid="Jordan Erifried's iPhone", auth=(WLAN.WPA2, "Jordan2002")) while not wlan.isconnected(): machine.idle() print("WiFi connected succesfully") print(wlan.ifconfig()) #see other available routers response = urequests.post("http://cow.flcl.co:3000/email", data="*****@*****.**" + " " + str(si.temperature()) + "") #response = urequests.post("http://cow.flcl.co:3000/sms", data = "+250782330752" + " " + str(t_ambient) + "") response.close()
def update(key, data): if not station.isconnected(): station.connect(ssid, pwd) print('Connecting...') sleep(3) if station.isconnected(): print('connected') r = urequests.get(url1) results = r.json() print(results) results[key] = data r = urequests.post(url1, data=json.dumps({"data": results}), headers=headers) #print(r.json) print("end")
def post_location(latitude, longitude): try: url = "https://api.wia.io/v1/locations" headers = { "Authorization": "Bearer " + DEVICE_SECRET_KEY, "Content-Type": "application/json" } json_data = {"latitude": latitude, "longitude": longitude} if json_data is not None: print(json_data) req = requests.post(url=url, headers=headers, json=json_data) print(req.json()) return req.json() else: pass except: pass
def post_url(url, data): gc.collect() resp = None try: headers = { "Content-Type": "application/json", } resp = request.post(url, headers=headers, json=data) value = resp.json() except Exception as e: # Here it catches any error. if isinstance( e, OSError ) and resp: # If the error is an OSError the socket has to be closed. resp.close() value = {"error": e} gc.collect() return value
def sendNotification(stationAddress, message): print("Current time: {0}".format(time.ticks_ms())) plantHeader = {"Content-Type": "application/x-www-form-urlencoded"} plantData = { "value1": "{0}".format(stationAddress), "value2": "{0}".format(message) } plantDataEncoded = uUrlEncode(plantData) print("Current time: {0}".format(time.ticks_ms())) webResponse = urequests.post(webhookURL, data=plantDataEncoded, headers=plantHeader) print("Current time: {0}".format(time.ticks_ms())) print("Response: {0} to message: {1}".format(webResponse.text, plantData)) print(webResponse.content) print(webResponse.encoding) webResponse.close()
def post_var(device, value1, value2, value3): try: url = "https://industrial.api.ubidots.com/" url = url + "api/v1.6/devices/" + device headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"} # Here you can edit the labels data = build_json("Temperature", value1, "Smoke", value2, "Movement", value3) if data is not None: print(data) req = requests.post(url=url, headers=headers, json=data) return req.json() else: pass except: pass
def sendMeasurementToCoT(self, sensorNr, distance, voltage): global data global response self.rtcNow = self.rtc.now() #print("source: {id %s}, time: %s-%02d-%02dT%02d:%02d:%02d.%03d+00:00, type: parking_sensor, c8y_measurement: {measuredDistance-%02d: {value: %s, unit: %02d}%s}}" % (self.deviceCoTID, self.rtcNow[0], self.rtcNow[1], self.rtcNow[2], self.rtcNow[3], self.rtcNow[4], self.rtcNow[5], self.rtcNow[6] // 1000, sensorNr, distance, sensorNr, vol)) data='{"source": {"id": "%s"}, "time": "%s-%02d-%02dT%02d:%02d:%02d.%03d+00:00", "type": "parking_sensor", "c8y_measurement": {"measuredDistance-%02d": {"value": %s, "unit": "cm"}, "batteryPercentage-%02d": {"value":%s, "unit": "per" }}}' % (self.deviceCoTID, self.rtcNow[0], self.rtcNow[1], self.rtcNow[2], self.rtcNow[3], self.rtcNow[4], self.rtcNow[5], self.rtcNow[6] // 1000, sensorNr, distance, sensorNr, voltage) self.p("CoT", "Sending measurement to Cloud of Things > %s" % (data)) try: response = urequests.post("https://iotatst.ram.m2m.telekom.com/measurement/measurements", headers={"Authorization": "Basic %s" % self.authBase64, "Content-Type": "application/vnd.com.nsn.cumulocity.measurement+json", "Accept": "application/vnd.com.nsn.cumulocity.measurement+json"}, data=data) responseJSON = json.loads(response.text) if response.status_code != 201: print(response.status_code, response.text) except Exception as e: self.p("WARNING", "Could not send request to Cloud of Things (%s)" % (e)) self.CoTisConnected = False
def logDevice(urlPOST="https://www.octopusengine.org/iot17/add18.php"): from time import sleep_ms from urequests import post header = {} header["Content-Type"] = "application/x-www-form-urlencoded" deviceID = getUid() place = "octoPy32" logVer = int(libVer100) try: postdata_v = "device={0}&place={1}&value={2}&type={3}".format( deviceID, place, logVer, "log_ver") res = post(urlPOST, data=postdata_v, headers=header) sleep_ms(200) print("--- logDevice.ok") res.close() except Exception as e: print("--- Err.logDevice: {0}".format(e))
def connectWithMagic(url, magic): st = "4Tredir=http%3A%2F%2Fmsftconnect.com%2F&magic="+str(magic)+"&username=wifi&password=wifi" try: #Initiate the authentication by sending GET request to the redirected URL print("Logging in to the internet") r = urequests.get(url) r.close() #Complete the authentication by sending the form data to the required URL r = urequests.post(url[:url.find("?")], data=st, headers={'Content-Type': 'application/x-www-form-urlencoded'}) r.close() except IndexError: print("Already connected to the internet") except ValueError: print("The device was already logged in. Therefore, there was no URL")
def send(self, request_data): """ Submit telemetry data using HTTP POST request """ log.info('Sending HTTP request to %s', self.uri) log.debug('Payload: %s', request_data['payload']) import urequests response = urequests.post(self.uri, data=request_data['payload'], headers={'Content-Type': self.content_type}) if response.status_code in [200, 201]: return True else: message = 'HTTP request failed: {} {}\n{}'.format( response.status_code, response.reason, response.content) raise TelemetryTransportError(message)
def store(data): try: led.off() # print("HTTP posting to {}".format(config.db)) resp=urequests.post(config.db, data=data, headers={ 'Content-Type': 'text/plain' }) if resp.status_code!=204: print('HTTP response "{}", text: {} '.format(resp.reason,resp.text)) print("DB ERROR") # print("OK") led.on() return(True) except Exception as e: print('HTTP error: {}'.format(e)) return(False)
def io_post(group, aq): # Adafruit.io POSTing import json, urequests, sleep headers = {'X-AIO-Key': aio_key,'Content-Type': 'application/json'} url='https://io.adafruit.com/api/v2/'+user+'/groups/'+group+'/data' print('URL is:', url) aqlist = [] for key, value in aq.items(): aqlist.append({"key": key, "value": value}) #print("Mylist", aqlist) api_list = { "location": {"lat": lat, "lon": lon}, "feeds": aqlist} data = json.dumps(api_list) # POST response try: response = urequests.post(url, headers=headers, data=data) print(response.text) except OSError as err: print("OS error: {0}".format(err)) sleep.init(sleep_interval) else: response.close()
def store(self, cat): '''store cat statistics in db''' # POST data to influxdb try: self.display.msg("Uploading...") print("HTTP posting to {}".format(config.db)) req_data = 'measurements,cat={},scale={} weight={},food={},feed_daily={}'.format(cat.state.name, config.id, cat.state.weight, cat.ate_session, cat.state.feed_daily) resp=urequests.post(config.db, data=req_data, headers={ 'Content-Type': 'text/plain' }) print('HTTP response "{}", text: {} '.format(resp.reason,resp.text)) if resp.status_code!=204: self.display.msg("Database error.") else: self.display.msg("") return True except Exception as e: print('HTTP error: {}'.format(e)) self.display.msg("Network error.", timeout=None) return False
json_object = { "logger": config.LOGGER_ID, "humidity": humidity, "temperature_celsius": temperature, "heat_index_celsius": heat_index } json_text = json.dumps(json_object) print(json_text) if not connect(config.CONNECTION_TIMEOUT_SEC): print("No connection, Skipping") # TODO save data and send later (ensure server support for multiple logs post) if (time.time() - last_connected) > config.MAX_ALLOWED_OFFLINE_TIME_SEC: machine.reset() else: response = urequests.post(config.LOGGING_URL, data=json_text, headers={"content-type": "application/json"}) print(response.text) last_connected = time.time() except OSError as os_error: if os_error.args[0] == 110: # ETIMEDOUT print("Cannot access sensor: timed out") # TODO Handle other errors time.sleep(config.MEASUREMENT_INTERVAL_SEC)
bme = BME280.BME280(i2c=i2c) temp = bme.temperature hum = bme.humidity pres = bme.pressure # uncomment for temperature in Fahrenheit #temp = (bme.read_temperature()/100) * (9/5) + 32 #temp = str(round(temp, 2)) + 'F' sensor_readings = {'value1':temp[:-1], 'value2':hum[:-1], 'value3':pres[:-3]} print(sensor_readings) request_headers = {'Content-Type': 'application/json'} request = urequests.post( 'http://maker.ifttt.com/trigger/bme280/with/key/' + api_key, json=sensor_readings, headers=request_headers) print(request.text) request.close() except OSError as e: print('Failed to read/publish sensor readings.') sleep(10) #ESP8266 deep_sleep(ms_sleep_time) #ESP32 #machine.deepsleep(ms_sleep_time)
def post(json): r=urequests.post(url,json=json,headers=headers) return r