def motorcycleability(): """ Display forecast information with regard to motorcycle riding Get rain etc. for next time 8-10am block or next 4-6pm block """ # ntptime.settime() # machine.RTC().datetime((2018, 5, 13, 0, 10, 59, 40, 0)) # Test top of the hour connect_and_sync() url = "https://api.darksky.net/forecast/73aaae75acf106e62591ff108c364d81/37.8267,-122.4233" headers = {'Accept-Encoding':'gzip'} r = urequests.get(url, headers = headers) print(r.content) j = json.loads(r.content) rain = j['hourly']['data'][0]['precipProbability'] i = 0 for h in j['hourly']['data']: t = h.get('time') p = h.get('precipProbability') np[i] = (255 * p, 0 ,0 ) np.write() nr = False lb = -1 while True: t = machine.RTC().datetime() h = t[4] print("time after time") time.sleep(100)
def ddnsupdate(self): if self.enabled(): import urequests as req from ubinascii import b2a_base64 auth = b2a_base64('{}:{}'.format(self.cfg['user'], self.cfg['pass'])) headers = { 'Authorization': 'Basic {}'.format(auth) } url = '{}?{}={}'.format(self.cfg['url'], 'hostname', self.cfg['host']) res = req.get(url, headers=headers) logger.info(res.status_code) res.close()
def main(): import urequests, json, time, machine from machine import Pin result = None last_price = -1 trend = 0 # Inicializar pines pin_red = Pin(PIN_RED, Pin.OUT, Pin.PULL_UP) pin_green = Pin(PIN_GREEN, Pin.OUT, Pin.PULL_UP) while True: response = urequests.get("{0}?fsym={1}&tsyms={2}".format(API_BASE_URL, CRYPTOCURRENCY, CURRENCY)) result = response.json() response.close() if result: current_price = result[CURRENCY] if last_price > -1: # If debug if DEBUG: print ("LAST: " + str(last_price)) print ("CURRENT: " + str(current_price)) if last_price <= current_price: trend = 1 else: trend = 0 last_price = current_price print_trend(trend, pin_red, pin_green) time.sleep(FRECUENCY)
async def get_offset(self): while True: while not self.sta_if.isconnected(): await sleep(1) while self.sta_if.isconnected(): try: worldtime = get("http://worldtimeapi.org/api/ip") worldtime_json = worldtime.json() offset = worldtime_json["utc_offset"] self.offset_hour = int(offset[1:3]) self.offset_minute = int(offset[4:6]) if offset[:1] == "-": self.offset_hour = -self.offset_hour print("> Timezone offset: {}h{}m".format(self.offset_hour, self.offset_minute)) # Wait an hour before updating again await sleep(3600) except Exception as e: print("> NtpTime.get_offset error: {} / worldtime: {}".format(e, worldtime)) await sleep(15)
def monitor(): #mengambil data dari accuweather r = urequests.get( "http://apidev.accuweather.com/currentconditions/v1/202242.json?language=en&apikey=hoArfRosT1215" ).json() suhu = r[0]['Temperature']['Metric']['Value'] waktu = r[0]['LocalObservationDateTime'] jam = waktu[11] + waktu[12] + waktu[13] + waktu[14] + waktu[15] #mengambil data dari ubidots print("Pada jam:", jam) print("Suhu di Tangerang adalah", suhu, "C") if suhu < 26: np[0] = (0, 0, 255) np[1] = (0, 0, 255) np[2] = (0, 0, 255) np.write() else: np[0] = (255, 255, 0) np[1] = (255, 255, 0) np[2] = (255, 255, 0) np.write() sleep(1)
def Module_Version_Check(self, Name): # get modules md5 file from server Server_md5 = urequests.get("http://" + self.Server + ":" + self.Server_Port + "/Modules/" + uos.uname().sysname + "/" + Name + ".md5") # Convert responce to text Server_md5 = Server_md5.text try: with open('/lib/' + Name + '.md5', 'r') as f: Local_md5 = f.read() # if we cant get local md5 fail check except: raise self.Error( "Module_Version_Check: local md5 missing for module: " + Name) # Check if local and server md5 matches if Server_md5 == Local_md5: return else: raise self.Error( "Module_Version_Check: Local and Server md5 not matching for module: " + Name)
async def remove_hist(): files = ['piec.hist', 'termometr.hist'] aliases = get_config("aliases", {}) for alias in aliases: fn = alias.split("=")[0] if fn != "": files.append(fn) for hf in files: try: if get_config("remote_hist_url", "") != "": try: url = "%s/remove_hist?file=%s" % (get_config( "remote_hist_url", ""), hf) resp = urequests.get(url) resp.close() except Exception as uer: sys.print_exception(uer) await lock_file(hf) os.remove(hf) unlock_file(hf) except Exception as err: print(err)
def bootstrap(imsi: str, server: str, auth: str) -> str: """ Claim SIM identity at the ubirch backend and return SIM applet PIN to unlock crypto functionality. Throws exception if bootstrapping fails. :param imsi: the SIM international mobile subscriber identity (IMSI) :param server: the bootstrap service URL :param auth: the ubirch backend password :param debug: enable debug output :return: the PIN to authenticate against the SIM card with """ url = 'https://' + server + '/ubirch-web-ui/api/v1/devices/bootstrap' headers = { 'X-Ubirch-IMSI': imsi, 'X-Ubirch-Credential': binascii.b2a_base64(auth).decode().rstrip('\n'), 'X-Ubirch-Auth-Type': 'ubirch' } r = requests.get(url, headers=headers) if r.status_code == 200: print(">> bootstrapping successful\n") info = json.loads(r.content) return info['pin'] else: raise Exception("request to {} failed with status code {}: {}".format( url, r.status_code, r.text))
def deploy(url=URL): import sys import os import lib.shutil as shutil import upip_utarfile as utarfile import urequests res = urequests.get(url) if not res.status_code == 200: return def exists(path): try: os.stat(path) return True except: return False t = utarfile.TarFile(fileobj = res.raw) for f in t: print("Extracting {}: {}".format(f.type, f.name)) if f.type == utarfile.DIRTYPE: if f.name[-1:] == '/': name = f.name[:-1] else: name = f.name if not exists(name): os.mkdir(name) else: extracted = t.extractfile(f) with open(f.name, "wb") as fobj: shutil.copyfileobj(extracted, fobj)
def get_current_playing_track(): global g_spotify_token headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(g_spotify_token), } try: r = urequests.get(SPOTIFY_API_CURRENTLY_PLAYING_URL, headers=headers) if len(r.content) == 0: # if status code is 204, no track is played. It's not error if r.status_code == 204: return None else: # warn about status_code lcd.println('header status is: {}'.format(r.status_code)) return None return r.json() except Exception as e: lcd.println('Exception(get_current_playing_track): ' + str(e)) lcd.println('Error: ' + str(r.content)) raise e finally: r.close()
def getInfo(auth, type_="light"): #获取信息 # 电灯"&miType=light" #插座"&miType=outlet" #多个插座"&miType=multi_outlet" #传感器&miType=sensor" #设置设备类型 host = 'https://iot.diandeng.tech' url = '/api/v1/user/device/diy/auth?authKey=' + auth + "&miType=" + type_ + "&version=1.2.2" print(host, url) data = ujson.loads(urequests.get(host + url).text) ''' deviceName = data['detail']['deviceName'] iotId = data['detail']['iotId'] iotToken = data['detail']['iotToken'] productKey = data['detail']['productKey'] uuid = data['detail']['uuid'] broker = data['detail']['broker']] ''' return data
def weatherUtilInfo(): # 声明为全局变量 global weatherUrl # 使用get方法 返回的值为对象 属于response类 getWeatherInformation = urequests.get(weatherUrl) # 获取getInformation的json类型 weatherInformationDict = getWeatherInformation.json() #天气信息 weatherToday = weatherInformationDict["weatherinfo"]["weather"] #尝试打印 #提取字符当中的单个字符 '-'表示从后向前取字符 weatherFlag = weatherToday[-1:] if weatherFlag == "晴": display.write_hex(0xAAAA) elif weatherFlag == "云": display.write_hex(0xBBBB) elif weatherFlag == "阴": display.write_hex(0xCCCC) elif weatherFlag == "雨": display.write_hex(0xDDDD) else: display.write_hex(0xFFFF) print(weatherFlag) return
def weather_suitable_for_watering(): """Uses the Yahoo Weather API to check for weather.""" yql_url = "http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20woeid%20%3D%20818717&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys" result = get(yql_url) data = loads(result.text) print("A") print(data) if 20 <= get_hours() < 23: # Evening - Check forecast for tomorrow. weather_code = data['query']['results']['channel']['item']['forecast'][ 1]['code'] del yql_url, result, data, created return weather_code in [ 19, 20, 21, 22, 26, 27, 28, 29, 30, 31, 32, 33, 34, 36 ] else: # Morning - Check forecast for today. print("b") weather_code = data['query']['results']['channel']['item']['forecast'][ 0]['code'] print("c") del yql_url, result, data, created return weather_code in [ 19, 20, 21, 22, 26, 27, 28, 29, 30, 31, 32, 33, 34, 36 ]
def main(): ssid = "test" password = "******" lcd = lcd_init() wifi_connect(ssid, password, lcd) # you can find cityid on this page: # https://gitee.com/wangjins/weather_api/blob/master/city.json cityid = "101020100" url = "http://www.tianqiapi.com/api/?version=v6&cityid=" + cityid + "&appid=65251531&appsecret=Yl2bzCYb" r = requests.get(url) data = json.loads(r.content.decode()) lcd.text("%s" % data["date"], 10, 0, 24) lcd.text("City: ShangHai", 10, 105, 24) # prints the string at 32 font size at position (0, 48) lcd.text("Humidity: %s" % data["humidity"], 10, 135, 24) lcd.text("Temp: %s - %s" % (data["tem2"], data["tem1"]), 10, 165, 24) image = "pictures/" + data[ "wea_img"] + ".bmp" # (xue, lei, shachen, wu, bingbao, yun, yu, yin, qing) lcd.show_bmp(190, 166, image)
def import_from_web(): while True: global dict_from_web dict_from_web = urequests.get(url).json() #print(dict_from_web) global count global last_dict_from_web global task global time global category global now_hour global task_now global GMT0time global local_hour #while dict_from_web: task = dict_from_web["task"] time = dict_from_web["time"] category = dict_from_web["category"] GMT0time = dict_from_web["current time"] if GMT0time > 16: local_hour = (GMT0time + 7) - 24 else: local_hour = GMT0time + 7 sleep(10)
def fetch_score(team_id): """ Function to get the score of the game depending on the chosen team. Inputs the team ID and returns the score found on web. """ # assign it somethign so it won't cause problems if get(url) fails score = 0 # Set URL depending on team selected url = '{0}schedule?teamId={1}'.format(NHL_API_URL, team_id) # Avoid request errors (might still not catch errors) try: response = requests.get(url) score = response.json() if int(team_id) == int(score['dates'][0]['games'][0]['teams']['home']['team']['id']): score = int(score['dates'][0]['games'][0]['teams']['home']['score']) else: score = int(score['dates'][0]['games'][0]['teams']['away']['score']) # Print score for test # print("Score: {0} Time: {1}:{2}:{3}".format(score, now.hour, now.minute, now.second)) # print("Score: {0}".format(score)) response.close() return score except: print("Error encountered, returning -1 for score") return -1
def turn_pointer(): # This is how you do a get call using urequests.get. It returns a string in json format ret = urequests.get(url).json() # ret is a long json string. You can parse the temperature data only by using the following code temp_in_kelvin = ret['main']['temp'] # the temperature in kelvin city_name = ret['name'] # you can access other information in 'ret' by changing the 'main' , 'temp' or 'name' # to see what other information is contained in ret, remove the comment '#' sign from the code below # print(ret) temp_in_celsius = round(temp_in_kelvin -273.15) # temperature conversion to celsius print(temp_in_celsius) # prints the data # each degree of temperature should turn the pointer by one unit_degree unit_degree = angle_bw_blueandred / (red_temp-blue_temp) # the pointer should turn turn_angle degrees to represent the temp_in_celsius degree temperature turn_angle = unit_degree * temp_in_celsius # move the pointer to turn_angle degrees pointer.run_target(20,turn_angle) return temp_in_celsius, city_name
def checkForUpdate(): print("Currently running Homital-L0 %s" % ('1.0.0')) print("Searching for updates...") try: res = requests.get(SERVER_ADDR + '/device/updates/homital-l0', headers={'Authorization': 'Bearer ' + TOKEN}) rj = res.json() res.close() if rj['success'] == True: print('Versions available:') rj['versions'].sort() #only work for single number versions for v in rj['versions']: print(" %s" % (v, )) if rj['versions'][-1] > '1.0.0': print("New version available: %s" % (rj['versions'][-1], )) print( "But sadly I cannot automatically install the update yet :<" ) print("You can try installing the update yourself") print("See %s" % ("https://github.com/Homital/Homital-L0")) else: print("Already running the latest version!") except: print("Something went wrong when checking for updates, skipping...")
def get_weather(location): url = BASE_URL + '?q=' + location + '&' url += 'units=metrics&lang=de&APPID=' + API_KEY response = urequests.get(url) return ujson.loads(response.text)
sleep(1.0) led.value(0) print("desligado") name = "Francisco" temp = 12.3 humid = 89 data = {"name": name, "temp": temp, "humid": humid} json = ujson.dumps(data) headers = {'Content-Type': 'application/json'} print(json) while True: response = urequests.post("http://192.168.25.54:8080/temphumid/send", data=json, headers=headers) print("send") print(response.text) response = urequests.get("http://192.168.25.54:8080/temphumid/verifica", data=json, headers=headers) print(response.text) if (response.text == "on"): led.value(1) else: led.value(0) sleep(2.0)
def bitcoin_usd(): res = urequests.get("https://api.coinpaprika.com/v1/tickers/btc-bitcoin") btcusd = res.json()['quotes']["USD"]["price"] return float(btcusd)
try: import urequests as requests except ImportError: import requests r = requests.get("https://api.telegram.org/bot") print(r) print(r.content) print(r.text) # You can access .content multiple times of course print(r.content) print(r.json()) # It's mandatory to close response objects as soon as you finished # working with them. On MicroPython platforms without full-fledged # OS, not doing so may lead to resource leaks and malfunction. r.close()
def call(): try: r = requests.get(WEBHOOK_URL) print(r.text) except Exception as e: print(e)
def notify(): try: r = requests.get(webhook_url) print(r.text) except Exception as e: print(e)
def lineNotify(msg ,sensorID): url="http://"+serverip+"/get5.php?msg="+msg +"&sensorID="+sensorID r=urequests.get(url) return r.text #status_code
def send_data(sensor_type, sensor_data): mac = str(ubinascii.hexlify(wlan.config('mac')), 'ascii') params = '?token=' + CONST_APITOKEN + '&command=send_data&device_id=' + mac + '&name=' + sensor_type + '&data=' + str( sensor_data) resp = urequests.get(CONST_SERVERURI + params) print(resp.json())
lora = LoRa(mode=LoRa.LORA, rx_iq=True, region=LoRa.EU868) lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) lora_sock.setblocking(False) import urequests as requests URL = "http://192.168.43.227:3333/lopy?" while (True): recv_pkg = lora_sock.recv(512) # check if data received has any message if (len(recv_pkg) > 2): recv_pkg_len = recv_pkg[1] # unpack to regular python strings device_id, pkg_len, msg = struct.unpack( _LORA_PKG_FORMAT % recv_pkg_len, recv_pkg) print('Device: %d - Pkg: %s' % (device_id, msg)) gps = msg.split(":")[0] gps1 = gps[1:] gps2 = gps1[:-1] new_url = "{}coord={}".format(URL, gps2) r = requests.get(URL) r.close() # pack to send back data was received ack_pkg = struct.pack(_LORA_PKG_ACK_FORMAT, device_id, 1, STATUS_CODE_GOOD) lora_sock.send(ack_pkg)
# Пример получения данных о погоде от Яндекс # Кабинет разработчика https://developer.tech.yandex.ru/?from=commercial в котором нужно получит ключ доступа к API import urequests, json url = "https://api.weather.yandex.ru/v1/informers?lat=55.753215&lon=37.622504" # Moscow key = {'X-Yandex-API-Key': 'здесь должен быть ключ'} gets = urequests.get(url, headers=key) k = gets.json() print(k)
# while True: # for a in range(len(s)): # display.fill(0) # display.text(s[a:a + 4], 0, 0, 1) # for i in range(0, 8): # display.scroll(-1, 0) # display.show() # time.sleep(0.5) while 1: apiURL1 = '{url}?q={city}&appid={key}'.format( url='http://api.openweathermap.org/data/2.5/weather', city='Taipei', key='34b1feab0ac8361b882a567b840aee21') r = req.get(apiURL1) if r.status_code != 200: print("Bad request") else: print("Data saved") data = ujson.loads(r.text) n_time = time.localtime(ntptime.time() + 28800) print('correct:', n_time ) # (year,month,day,hours,minutes,seconds,weekdays,subseconds) rtc = machine.RTC() rtc.datetime(n_time[0:3] + (0, ) + n_time[3:6] + (0, )) print('correct adjusted: ', rtc.datetime() ) # (year,month,day,weekday,hours,minutes,seconds,subseconds) clock = data[
def main(): global __sensorname, __deviceid, __functionSelect, __waterOn, __functionSelectLast testfornetwork() debug = False __sensorname = 'switch-user' __deviceid = getdeviceid() if debug: __sensorname += "-" + __deviceid + '-debug' mySensorRegistation = SensorRegistation(restHost, __deviceid) mySensorRegistation.register(__sensorname, 'Hardware', 'JH') myheartbeat = HeartBeat(restHost, __deviceid) myheartbeat.beat() mytime = TimeTank(__deviceid) while not mytime.settime(): pass rtc = RTC() sampletimes = [1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56] samplehours = [1, 6, 12, 18] isMinuteProcess = 0 lastMin = 0 gethour = 0 __functionSelect = __functionSelectPin.value() __waterOn = __waterOnPin.value() if __functionSelect: __np.colour(irrigationLed, 'indigo') __np.colour(hoseLed, 'purple') else: __np.colour(irrigationLed, 'purple') __np.colour(hoseLed, 'indigo') if __waterOn: __np.colour(pumpLed, 'purple') else: __np.colour(pumpLed, 'green') __np.write() while True: timeNow = rtc.datetime() currHour = timeNow[4] currMinute = timeNow[5] if currMinute not in sampletimes and isMinuteProcess == 0: isMinuteProcess = 1 if currMinute in sampletimes and isMinuteProcess == 1: isMinuteProcess = 0 if lastMin != currMinute: lastMin = currMinute myheartbeat.beat() if currHour not in samplehours and gethour == 0: gethour = 1 if currHour in samplehours and gethour == 1: gethour = 0 local = utime.localtime() while not mytime.settime(): pass # Read switch inputs __functionSelect = __functionSelectPin.value() __waterOn = __waterOnPin.value() functionStateChanged = False sensorValue = 0 # Check against the last input if __functionSelect != __functionSelectLast: if __functionSelect: __np.colour(irrigationLed, 'indigo') __np.colour(hoseLed, 'purple') else: __np.colour(irrigationLed, 'purple') __np.colour(hoseLed, 'indigo') functionStateChanged = True __functionSelectLast = __functionSelect # Set the last pointers # print('if ( __functionSelect != __functionSelectLast ):') if __waterOn != __waterOnLast: if __waterOn: # water on __np.colour(pumpLed, 'purple') else: # water off __np.colour(pumpLed, 'green') functionStateChanged = True __waterOnLast = __waterOn # Set the last pointers # print('if ( __waterOn != __waterOnLast ):') if functionStateChanged: if __functionSelect: sensorValue = 1 else: sensorValue = 2 if not __waterOn: # water on sensorValue += 4 url = "http://192.168.86.240:5000/sensorStateWrite/{0}/{1}/{2}" url = url.replace('{0}', __deviceid) # sensor id url = url.replace('{1}', __sensorname) # sensor type url = url.replace('{2}', str(sensorValue)) # sensor value print(url) try: response = urequests.get(url) print(response.text) response.close() except: print('Fail www connect...') __np.write()
from machine import Pin, reset import utime import urequests as requests import ujson as json # Creado por Daniel Alvarez ([email protected]) para curso de Python de EOI (eoi.es) # la conexion a wifi la hacemos en boot.py codigo_cuidad = "773692" # Codigo con el que metaweather identifica a Santa Cruz url = "https://www.metaweather.com/api/location/{}/".format(codigo_cuidad) r = requests.get(url) if r.status_code is not 200: print( "Error al acceder a metawether. Codigo de estado {} Contenido:".format( r.status_code)) print(r.content) utime.sleep(10) reset() # Si llega hasta aqui es por que status code que respondió la API es 200 (OK) datos = r.content.decode( ) # content es un array de bytes, lo pasamos a cadena de texto normal # print(resultado) # datos en este punto es un string que contiene la respuesta de la api en formato json datos_dict = json.loads( datos) # lo desserializamos convirtiendolo en un Diccionario # Esto es opcional: guardamos la respuesta en un fichero para consultarlo offline with open("datos_api.json", 'w') as f: f.write(datos) # Esto es opcional: si tenemos los datos en un fichero, lo podemos leer asi
from machine import Pin, PWM import time, network, urequests, dht, urandom sensor = dht.DHT11(Pin(0)) # 使用 D3 腳位取得溫溼度物件 led = Pin(2, Pin.OUT) sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect("bocheng", "123456789") while not sta_if.isconnected(): led.value(0) pass led.value(1) while True: sensor.measure() temp = sensor.temperature() wet = sensor.humidity() hot_index = sensor.temperature() + sensor.humidity() * 0.1 iftttURL = "http://maker.ifttt.com/trigger/IotFinal/with/key/dZ3wwtgPxaXqjEqEoGoddb" urequests.get(iftttURL + "?value1=" + str(temp) + "&value2=" + str(wet) + "&value3=" + str(hot_index)) time.sleep(1800)
try: import urequests as requests except ImportError: import requests r = requests.get("http://api.xively.com/") print(r) print(r.content) print(r.text) print(r.content) print(r.json()) # It's mandatory to close response objects as soon as you finished # working with them. On MicroPython platforms without full-fledged # OS, not doing so may lead to resource leaks and malfunction. r.close()