def put(self,path,myData): """ this method put in a branch a Mydata. if a branch not exist, it will be creat. myData = {key :value} path = 'branch/' """ if self.auth is None: try: response = urequests.put(self.firebase+path+'.json', data = json.dumps(myData)) print("try send") except: print("put sem auth bugou") else: try: url = self.firebase+path+'.json?auth='+self.auth print (url, type(url)) print (myData) response = urequests.put(url, data = json.dumps(myData)) print("try send") except: print("put com auth bugou") try: response.close() except: print("close bugou")
def led1(turnonval): if turnonval > 100: Tag = "led1" Type = "BOOLEAN" Key = "Q6g3YI_v6cdfkAHHoV8RFSzG-3ANPXGhhV0MfbIrm-" urlBase = "https://api.systemlinkcloud.com/nitag/v2/tags/" urlTag = urlBase + Tag urlValue = urlBase + Tag + "/values/current" headers = {"Accept": "application/json", "x-ni-api-key": Key} angle = str(True) propName = {"type": Type, "path": angle} propValue = {"value": {"type": Type, "value": angle}} print(urequests.put(urlTag, headers=headers, json=propName).text) print(urequests.put(urlValue, headers=headers, json=propValue).text) else: Tag = "led1" Type = "BOOLEAN" Key = "Q6g3YI_v6cdfkAHHoV8RFSzG-3ANPXGhhV0MfbIrm-" urlBase = "https://api.systemlinkcloud.com/nitag/v2/tags/" urlTag = urlBase + Tag urlValue = urlBase + Tag + "/values/current" headers = {"Accept": "application/json", "x-ni-api-key": Key} angle = str(False) propName = {"type": Type, "path": angle} propValue = {"value": {"type": Type, "value": angle}} print(urequests.put(urlTag, headers=headers, json=propName).text) print(urequests.put(urlValue, headers=headers, json=propValue).text)
def wash_start(pir_pin): led_pin_numbers = [12, 13, 14, 25, 26, 32] success_seconds = 20 seconds_active = 0 #Make sure all the pins are off for pin in led_pin_numbers: Pin(pin, Pin.OUT).off() #Notify server washing event is active response = urequests.post(post_url(), headers = {"content-type": "application/json", "content-length": "0"}).json() end_url = update_url(response['id']) #Monitor washing event v = pir_pin.value() while v == 1: seconds_active += 1 #Lite LEDs pins_to_light = (seconds_active / success_seconds) * len(led_pin_numbers) if(pins_to_light <= len(led_pin_numbers)): for index in range(0, pins_to_light): Pin(led_pin_numbers[index], Pin.OUT).on() #Take a rest, then grab a new value time.sleep(1) v = pir_pin.value() #Washing complete, notify server urequests.put(end_url, headers = {"content-type": "application/json", "content-length": "0"}).json() #Turn off LED's for pin in led_pin_numbers: Pin(pin, Pin.OUT).off()
def Create_SL(Tag, Type): urlBase, headers = SL_setup() urlTag = urlBase + Tag propName = {"type": Type, "path": Tag} try: urequests.put(urlTag, headers=headers, json=propName).text except Exception as e: print(e)
def put(self,value): propName={"type":self.type,"path":self.tag} propValue = {"value":{"type":self.type,"value":value}} try: setTag = urequests.put(self.url_tag,headers=self.headers,json=propName).text setValue = urequests.put(self.url_value,headers=self.headers,json=propValue).text except: setTag = 'error' setValue = 'error' return setTag,setValue
def Create_SL(Tag, Type,place): if place =='home': key = 'zpJ4VYEeaRsGM016V2EtWdH5IHSol0qB-O_YoqkTWW' else: key = 'bvd8X9LweQY9o2eP1NYL-p8mLL9wMAk6YYOnYSiIo0' urlBase, headers = SL_setup(key) urlTag = urlBase + Tag propName={"type":Type,"path":Tag} try: urequests.put(urlTag,headers=headers,json=propName).text except Exception as e: print(e)
def gaugevalue(turningval): Tag = "tachovalue" Type = "DOUBLE" Key = "Q6g3YI_v6cdfkAHHoV8RFSzG-3ANPXGhhV0MfbIrm-" urlBase = "https://api.systemlinkcloud.com/nitag/v2/tags/" urlTag = urlBase + Tag urlValue = urlBase + Tag + "/values/current" headers = {"Accept": "application/json", "x-ni-api-key": Key} angle = str(turningval) propName = {"type": Type, "path": angle} propValue = {"value": {"type": Type, "value": angle}} print(urequests.put(urlTag, headers=headers, json=propName).text) print(urequests.put(urlValue, headers=headers, json=propValue).text)
def change_state(self, state='toggle'): if state == 'toggle': self.payload['on'] = not self.state['on'] elif state == 'on': self.payload['on'] = True elif state == 'off': self.payload['on'] = False else: # raise Exception, "Invalid state." raise Exception # payload = {'on': new_state} try: # url = "http://%s/api/%s/lights/%d/state" % (self.bridge.ip, self.api_token, self.id) # url = "http://" + self.bridge.ip + "/api/" + self.bridge.api_token + "/lights/" + self.id + "/state" self.res = requests.put(self.url, self.data) #r.raise_for_status() if self.res.status_code != 200: raise Exception # ret = r.json()[0] if not self.res.json()[0]['success']: # self.bridge.logger.error("Update state failed.") # raise Exception, "Update state failed." raise Exception else: self.state['on'] = self.payload['on'] except Exception: # self.bridge.logger.exception("Change State Request Caught exception. %(url)s %(payload)s") raise
def ex5(): """ Pipe 1:1 advances - read 1 sensor continuously at a high rate and send information to a REST service. """ import urequests # read sensor at high rate touch = machine.TouchPad(machine.Pin(4)) pipe_read = average(touch) g = consume(pipe_read, period=0.1) # send information to REST service publish = lambda g: (urequests.put('http://httpbin.com/anything/somevalue', data=dict(value=value)) for value in g) pipe_publish = publish(onchange(g, delta=1)) g = consume(pipe_publish, period=1) """ # or a one-liner - re-using created pipes pipe_read = lambda g: average(g) # to be reusable, pipes need to be a generator function pipe_publish = lambda g: publish(onchange(g, delta=1)) g = consume(consume(pipe_publish(consume(period=0.1, g=pipe_read(touch))))) # or a one-liner - fully declarative oneliner, no pipe reuse g = consume(period=1, g=consume(publish(onchange(delta=1, g=consume(period=0.1, g=average(touch)))))) """ # optionnally log pipe output g = published_values # it is what is is, actually while value in published_values: print('Sent REST message:', value)
def SL_Put(self, Tag, Type, Value): urlTag = self.SL_urlBase + Tag urlValue = self.SL_urlBase + Tag + "/values/current" propName = {"type": Type, "path": Tag} propValue = {"value": {"type": Type, "value": Value}} try: response = urequests.put(urlTag, headers=self.SL_headers, json=propName).text response = urequests.put(urlValue, headers=self.SL_headers, json=propValue).text response.close() return True except Exception as e: print(e) return False
def update_station(api_key, station_id, **kwargs): """HTTP 200 if successful""" url = "http://api.openweathermap.org/data/3.0/stations" url += "/{}".format(station_id) url += "?appid={}".format(api_key) header = {"Content-Type": "application/json"} response = urequests.put(url, data=kwargs["new_data"]) return response
def CallService(thing, servicename): urlValue = urlBase + 'Things/' + thing + '/Services/' + servicename try: response = urequests.put(urlValue, headers=headers) print(response.text) response.close() except RuntimeError as e: print('error with AddtoTable', e)
def main(): sensor = machine.Pin(4, machine.Pin.IN, machine.Pin.PULL_UP) while True: value = sensor.value() oled.text(str(value), 0, 40) oled.clear() if value: urequests.put( 'https://api.netpie.io/topic/Testeiei/Test?retain&auth=wd37U6RPWfA0Ku3:en3QR4Emkz8EsWlMNXEAX3Xgc', data=str(value)) time.sleep_ms(200) oled.clear() else: urequests.put( 'https://api.netpie.io/topic/Testeiei/Test?retain&auth=wd37U6RPWfA0Ku3:en3QR4Emkz8EsWlMNXEAX3Xgc', data=str(value)) time.sleep_ms(200) oled.clear()
def get_sentence(self): sentence = urequests.put('http://' + self.server_address + '/api/v1/nmea_faker/sentence', json={ 'lat': '123', 'lon': '456' }, headers={'content-type': 'application/json'}) self.uart.write(sentence.text) return (sentence.text)
def Put(thing, property, type, value): urlValue = urlBase + 'Things/' + thing + '/Properties/*' propValue = {property: value} try: response = urequests.put(urlValue, headers=headers, json=propValue) print(response.text) response.close() except RuntimeError as e: print('error with Put', e)
def Put_SL(Tag, Type, Value): urlBase, headers = SL_setup() urlValue = urlBase + Tag + "/values/current" propValue = {"value": {"type": Type, "value": Value}} try: reply = urequests.put(urlValue, headers=headers, json=propValue).text except Exception as e: print(e) reply = 'failed' return reply
def Put(thing, property, type, value): urlValue = urlBase + 'Things/' + thing + '/Properties/*' propValue = {property: value} # assume that the tag is already created - urequests.put(urlTag,headers=headers,json=propName).text try: response = urequests.put(urlValue, headers=headers, json=propValue) print(response.text) response.close() except: print('error')
def put(self, path, myJson): try: url = self.firebase + path + '.json' if self.auth == None else self.firebase + path + '.json?auth=' + self.auth response = urequests.put(url, data=json.dumps(myJson)) #return response except: print("PUT Error?") try: response.close() except: print("Close Error?")
def send_to_system_link(Tag, Type, Value, key): print("Sending to system link") urlBase, headers = setup_systemlink(key) urlVal = urlBase + Tag + "/values/current" propVal = {"value": {"type": Type, "value": Value}} try: reply = urequests.put(urlVal, headers=headers, json=propVal).text except Exception as e: print(e) reply = 'failed' return reply
def Put_SL(Tag, Type, Value): #Put_SL() takes the tag, type, and value of the tag and writes it to the website (SLC) urlBase, headers = SL_setup() urlValue = urlBase + Tag + "/values/current" propValue = {"value":{"type":Type,"value":Value}} try: reply = urequests.put(urlValue,headers=headers,json=propValue).text except Exception as e: print(e) reply = 'failed' return reply
def TW_Put(self, thing, property, type, value): urlValue = self.TW_urlBase + 'Things/' + thing + '/Properties/*' propValue = {property: value} # assume that the tag is already created - urequests.put(urlTag,headers=headers,json=propName).text try: response = urequests.put(urlValue, headers=self.TW_headers, json=propValue) print(response.text) response.close() return True except Exception as e: print(e) return False
def put_url(url, data): gc.collect() resp = None try: resp = urequests.put(url, 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 Put_SL(Tag, Type, Value,place): if place =='home': key = 'zpJ4VYEeaRsGM016V2EtWdH5IHSol0qB-O_YoqkTWW' else: key = 'bvd8X9LweQY9o2eP1NYL-p8mLL9wMAk6YYOnYSiIo0' urlBase, headers = SL_setup(key) urlValue = urlBase + Tag + "/values/current" propValue = {"value":{"type":Type,"value":Value}} try: reply = urequests.put(urlValue,headers=headers,json=propValue).text except Exception as e: print(e) reply = 'failed' return reply
def addSensorValue(self): if self.distance < 10: data = { "sensor_ID": self.sensor, "sensorValue": 0, } r = urequests.post("http://172.20.10.3:8080/sensor_data/post/", json=data) r.close() put = urequests.put("http://172.20.10.3:8080/sensor/put/"+ str(self.sensor)+ "/", json=data) put.close() else: data = { "sensor_ID": self.sensor, "sensorValue": 1, } r = urequests.post("http://172.20.10.3:8080/sensor_data/post/", json=data) r.close() put = urequests.put("http://172.20.10.3:8080/sensor/put/"+ str(self.sensor)+ "/", json=data) put.close()
def fsRestPut(ipadr, qkey, qval, port=8080, ssl=False, timeout=2, path='/qsave'): ''' puts quantity value to restfull fshome api ''' url = 'https://' if ssl else 'http://' url += ipadr if port: url += ':%d' % port url += path url += '?qkey={}&qval={}'.format(qkey, qval) print("fsRestPut:{}".format(url)) rq = requests.put(url) return rq
def _register_device(self, url, sas_token): """ create new device identity in Azure IoT hub device registry """ body = '{deviceId: "%s"}' % self.device_id r = requests.put(url, headers={ 'Content-Type': 'application/json', 'Authorization': sas_token }, data=body) if r.status_code == 200: print("Registered device at hub: {}".format(r.text)) return _get_device_key(r) else: raise Exception( "!! Device not registered. Request failed with status code {}: {}" .format(r.status_code, r.text))
def recursiveCheck(sensorList, index=0): for i in range(index, len(sensorList)): chiller = sensorList[i] if chiller.sensorType == "DHT22": sensor = dht.DHT22(Pin(chiller.pin)) elif chiller.sensorType == "DHT11": sensor = dht.DHT11(Pin(chiller.pin)) else: print("sensor not supported") try: sensor.measure() temp = sensor.temperature() hum = sensor.humidity() temps.append(temp) hums.append(hum) except OSError as e: print('Failed to read sensor.') return data = { 'id': chiller.sensorId, 'type': chiller.sensorType, 'secret': secrets.secret, 'temperature': temp, 'humidity': hum } try: server = "http://192.168.1.11:5000/IoTChiller/" r2 = urequests.put(server + str(chiller_id), data=ujson.dumps(data), headers={'Content-Type': 'application/json'}) except OSError as e: print("Failed to send data to API") if hum is not None and temp is not None: print( f"The {chiller.sensorDesc} is at {temp} °C and {hum} % humidity" ) else: recursiveCheck(sensorList, i) return
def register(self): gc.collect() self._logger.debug('Registering...') body = {'registrationId': self._registration_id} try: body['data'] = {'iotcModelId': self._model_id} except: pass uri = "https://{}/{}/registrations/{}/register?api-version={}".format( self._endpoint, self._scope_id, self._registration_id, self._api_version) response = urequests.put( uri, data=json.dumps(body), headers=self._headers) operation_id = json.loads(response.text)['operationId'] response.close() sleep(5) creds = self._loop_assignment(operation_id) self._clean_imports() self._logger.debug(creds) return creds
async def send_data(self): global BOOK_STATUS while True: to_send = BOOK_STATUS.copy() to_send = self.send_serializer(to_send) r = None try: gc.collect() r = put(url=self.Meta.UPDATE_URL, json=to_send, headers=AUTH_HEADER) if r.status_code != 200: raise Exception("Failed", r.status_code, r.reason, r.text) except OSError as e: print("Error while sending data ", e) except Exception as e: print("Other exception caughted while sending", e) finally: if not r is None: r.close() await asyncio.sleep(15)
def __call__(self, *args, **kwargs): url = self.url for a in args: url += "/" + str(a) http_method = kwargs.pop('http_method', 'get' if not kwargs else 'put').lower() if http_method == 'put': r = requests.put(url, data=json.dumps(kwargs)) elif http_method == 'post': r = requests.post(url, data=json.dumps(kwargs)) elif http_method == 'delete': r = requests.delete(url) else: r = requests.get(url) if r.status_code != 200: raise QhueException("Received response {c} from {u}".format( c=r.status_code, u=url)) resp = r.json() if type(resp) == list: errors = [m['error']['description'] for m in resp if 'error' in m] if errors: raise QhueException("\n".join(errors)) return resp
# TCS34725 i2c = I2C(-1, Pin(5), Pin(4)) sensor = tcs34725.TCS34725(i2c) led = machine.Pin(12, machine.Pin.OUT) led.off() # Blink LED 2 times if network connects if sta_if.isconnected(): sta_if.ifconfig() led.on() time.sleep(0.5) led.off() time.sleep(0.5) led.on() time.sleep(0.5) led.off() # Sensor Setup sensor.active(True) sensor.gain(16) sensor.integration_time(402) time.sleep_ms(500) led.on() sensor_rgb = html_hex(sensor.read(True)) # HTTP Request URL Setup urequests.put("http://SIMPLE_LED_STRIP_IP/rgb?color=0x" + sensor_rgb) led.off()