Esempio n. 1
0
def send_slack_alert(duration):
    url = 'https://hooks.slack.com/services/WEBHOOK_ID' # slack webhook url
    if duration == "long":
        payload = '{"text": "Brett will be away for over an hour"}'
    elif duration == "mid":
        payload = '{"text": "Brett will be away for up to an hour"}'
    elif duration == "back":
        payload = '{"text": "Brett is back"}'
    urequests.request("POST", url, data=payload)
    print("Button pressed")
Esempio n. 2
0
 def forecast(self, appid, lat, lon):
     res = requests.request(
         "get",
         "https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&appid={}&units=imperial&exclude=current"
         .format(lat, lon, appid),
     )
     return res.json()
Esempio n. 3
0
def btime():
    btime = urequests.request(method='GET',
                              url='https://api.binance.com/api/v1/time',
                              data="")
    btime = json.loads(btime.text)
    btime = int(btime['serverTime'])
    return btime
Esempio n. 4
0
    def authorize(self):
        '''
        Makes an authorization request.
        '''

        if not self._discovered:
            print('Need to discover authorization and token endpoints.')
            return

        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        payload = {'client_id': self.client_id, 'scope': ' '.join(self.scopes)}
        encoded = urlencode(payload)
        r = requests.request('POST',
                             self._device_auth_endpoint,
                             data=encoded,
                             headers=headers)
        j = r.json()
        r.close()

        if 'error' in j:
            raise RuntimeError(j['error'])

        self._device_code = j['device_code']
        self.user_code = j['user_code']
        self.verification_url = j['verification_url']
        self._interval = j['interval']
        self._code_expires_in = j['expires_in']
        self._authorization_started = True
        message = 'Use code %s at %s to authorize the device.' % (
            self.user_code, self.verification_url)
        print(message)
    def events(self, limit=5):
        # Calendar id is part of the endpoint iself.
        endpoint = 'https://www.googleapis.com/calendar/v3/calendars/primary/events'
        start_time = today_rfc3339(hours_offset=-1)
        token = self.device_auth.token()
        authorization = 'Bearer %s' % (token)
        headers = {
            'Authorization': authorization,
            'Accept': 'application/json'
        }
        payload = {
            'maxResults': limit,
            'orderBy': 'startTime',
            'singleEvents': 'true',
            'timeMin': start_time,
            'key': API_KEY
        }
        encoded = urlencode(payload)
        full_url = '%s?%s' % (endpoint, encoded)
        r = requests.request('GET', full_url, headers=headers)
        j = r.json()
        r.close()

        if 'error' in j:
            raise RuntimeError(j)

        return self._parse_calendar_events(j)
Esempio n. 6
0
def send_data():
    global BPM
    global Flag
    while True:
        if Flag:
            temp = []
            # Preprocess
            for i, data in enumerate(BPM, 0):
                if data[1] == -1:
                    temp.append([i, 0])
                else:
                    temp.append([i, data[1]])
            headers = {'content-type': 'application/json'}
            mock_data = {'data': {'heartrate': temp}}
            del temp
            print('Routine Job Executed')
            # data = {'data': user_data}
            js = json.dumps(mock_data)
            gc.collect()
            res = urequests.request('POST',
                                    __ext.BASEURL,
                                    headers=headers,
                                    data=js)
            res.close()
            if BPM[-1][1] != -1:
                print('Reset Time Frame')
                BPM = [[n, -1] for n in range(60)]
            Flag = False

        sleep(0.1)
Esempio n. 7
0
    def writeToInfluxdb(self):

        try:
            url = "http://" + self.host + ":" + str(
                self.port) + "/write?db=" + self.db
            if self.debug:
                print(url)
            res = urequests.request("POST", url, self.data)
            self.data = ""
            if res.status_code == 400 or res.status_code == 401 or res.status_code == 404 or res.status_code == 413 or res.status_code == 500:
                if self.debug:
                    print("Probleem schrijven naar influxdb")
                    print(res.reason)
                    res.close()
                    return False
            else:
                print(res.status_code)
                res.close()
                return True

        except Exception as E:
            if self.debug:
                print(E)
            res.close()
            return False
Esempio n. 8
0
def runway(x, y):
    global url, output, img, headers, inputs, status, size, neuron, runway_set
    url = 'https://<runway-ml-model>.hosted-models.runwayml.cloud/v1/query'
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer <your id>'
    }
    inputs = {
        'layer': 'maxpool4 (max:480)',
        'neuron': x,
        'size': y,
        'transforms': False,
        'transform_min': 0.1,
        'transform_max': 0.5
    }
    try:
        req = urequests.request(method='POST',
                                url=url,
                                json=inputs,
                                headers=headers)
    except:
        status = req.status_code
        label1.set_text(str(status))
    output = json.loads((req.text))
    return output
def spinnerDemo(sessionID):
    xAverage, yAverage, zAverage, _, _ = sampleAndHoldAccel(10)
    #format its value to compress
    dataX, dataY, dataZ = "{0:.2f}".format(xAverage), "{0:.2f}".format(
        yAverage), "{0:.2f}".format(zAverage)
    dataTemp = "{0:.2f}".format(sampleAndHoldTemperature(10))

    #Checksum
    print(xAverage, yAverage, zAverage, dataTemp)
    sensor_data = dataX + ' ' + dataY + ' ' + dataZ + ' ' + dataTemp
    print('Hex: ' + str(sensor_data) + '[' + str(len(sensor_data)) + ']')

    #AES
    myCrypto = CryptAes(sessionID)
    myCrypto.encrypt(sensor_data)
    myHMAC = myCrypto.sign_hmac(sessionID)
    jsonData = myCrypto.send_mqtt(myHMAC)

    #IFTTT SHIT
    iftttDict = {}
    iftttDict['value1'] = myCrypto.nodeid + "|||" + str(
        sessionID
    ) + "|||" + dataX + "|||" + dataY + "|||" + dataZ + "|||" + dataTemp
    r = urequests.request(
        "POST",
        "https://maker.ifttt.com/trigger/IFTTT_ECE40862/with/key/g7HnGNBx3R7FfYQLrhVAIeqUGU3hXokCNEeRH3nHCad",
        json=iftttDict,
        headers={"Content-Type": "application/json"})
    print(r.text)

    #send to Topic
    client.publish(topic=sensorDataTopic, msg=jsonData)
Esempio n. 10
0
def receive_handler(topic, msg):
    global num, client, pub, temp_last
    print('Msg From Sensordata Topic:  ' + str(msg))
    r_led.value(0)
    pwm.init()
    #Crypt & Demo
    mycrp = CryptAes(bytes(str(num), 'uft-8'))
    fail_check = mycrp.verify_hmac(msg)
    if fail_check == 0:
        client.publish(topic=akTopic_pub, msg="Fail Authentication")
        pub = 1

    check, node_id, data_x, data_y, data_z, temp = mycrp.decrypt(msg)

    #Demo
    if (abs(data_x) > 0.8 or abs(data_y) > 0.8 or abs(data_z) > 1.2):
        r_led.value(1)
    if (temp_last):
        freq = pwm.freq() + int((temp_last - temp)) * 5
        pwm.freq(freq)
    if check:
        client.publish(topic=akTopic_pub, msg="Successful Decryption")
        temp_last = temp
        data = {}
        data['value1'] = node_id + '|||' + str(num) + '|||' + str(
            data_x) + '|||' + str(data_y) + '|||' + str(data_z) + '|||' + str(
                temp)
        r = urequests.request(
            "POST",
            "https://maker.ifttt.com/trigger/decryption/with/key/l2IcanZRKg_-1ny_9_Dhew-gadfK0vblGjpIJtCK0-w",
            json=data,
            headers={"Content-Type": "application/json"})
        print(r.text)
        pub = 1
Esempio n. 11
0
def post_to_slack(message):
    url = "Ur Slack URL"

    payload = "{\"text\":\"" + message + "\"}"
    headers = {
        'Content-type': "application/json",
    }
    response = urequests.request("POST", url, data=payload, headers=headers)
Esempio n. 12
0
def post_to_raspberry_flask():
    print('entered function')
    payload = json.dumps(moisture_reading())
    print(payload)
    url = "http://192.168.0.150:5000/moisture"
    headers = {'Content-Type': "application/json"}
    response = urequests.request("POST", url, data=payload, headers=headers)
    print(response.text)
Esempio n. 13
0
def post(url, params=None, **kw):
    if params != None:
        #todo: urllib.urlencode the parameters
        glue = "?"
        for k in params:
            url = url + "{}{}={}".format(glue, k, params[k])
            glue = "&"
    return urequests.request("POST", url, **kw)
Esempio n. 14
0
def price():
    response = urequests.request(
        method='GET',
        url="https://api.binance.com/api/v3/ticker/price?symbol=LTCUSDT",
        data="")
    if 'code' in response.text:
        raise Exception(response.text)
    print(response.json())
Esempio n. 15
0
def szzx_connection():
    res = urequests.request(config.SZZX_TEACHER_METHOD,\
     config.SZZX_TEACHER_URL,\
     data=config.SZZX_TEACHER_DATA,\
     headers=config.SZZX_TEACHER_HEADER)
    print('Connected')
    # Ping test
    res.close()
Esempio n. 16
0
    async def update_data(self):
        delay = self.interval * 1000

        while True:
            r = urequests.request(self.method, self.url, headers=self.headers)
            self.response_property.data = r.text
            r.close()

            await sleep_ms(delay)
Esempio n. 17
0
    async def update_data(self):
        delay = self.interval * 1000

        while True:
            r = urequests.request(self.method, self.url, headers=self.headers)
            self.p_response.value = r.text
            r.close()

            await asyncio.sleep_ms(delay)
Esempio n. 18
0
def get_latest_feed():
    try:
        url = "http://api.thingspeak.com/channels/{}/feeds/last.json?api_key={}".format(
            channel_id, api_key)
        resp = urequests.request("GET", url)
        jresp = resp.json()
        return jresp
    except:
        print("Couldn't fetch latest feed from cloud")
Esempio n. 19
0
def has_internet():
    try:
        resp = urequests.request("HEAD", "http://jsonip.com/")
        return True
    except OSError as ex:
        print("Internet OFF ", ex)
        print(dir(OSError))
        print(dir(ex))
        return False
Esempio n. 20
0
def stop_time_entry():
    auth_header_ = auth_header()
    resp = urequests.request(
        'GET',
        'https://www.toggl.com/api/v8/time_entries/current',
        headers=auth_header_)
    print(resp.content)
    data = json.loads(resp.content)['data']
    if data:
        time_entry_id = data['id']
        headers = {'Content-length': '0'}
        headers.update(auth_header_)
        resp = urequests.request(
            'PUT',
            'https://www.toggl.com/api/v8/time_entries/{}/stop'.format(
                time_entry_id),
            headers=headers)
        print(resp.content)
Esempio n. 21
0
def sendMQTT(nodeid, sessionID, x, y, z, t):
    url = "https://maker.ifttt.com/trigger/MOM/with/key/hLKtFm2TIKYMfXYWIAyx5dvgMpHRbTQDG3lCBRDsCOx"
    lib = {
        "value1":
        str(nodeid) + '|||' + str(sessionID) + '|||' + str(x) + '|||' +
        str(y) + '|||' + str(z) + '|||' + str(t)
    }

    r = urequests.request("POST", url,\
                      json=lib, headers={"Content-Type": "application/json"})
def __iot_get(request_url):
    if not codey.wifi_is_connected():
        print('-------> No network connection: ' + request_url)
        return ''
    print('======request_url: ' + request_url)
    res = urequests.request('GET',
                            request_url,
                            headers=__iot_get_request_header()).json()
    print(res)
    return res['data']
Esempio n. 23
0
def _request(device, target_url, method, body, headers):
  content = None
  if http != None:
    return _doRequest(device, target_url, method, body, headers)
  else:
    if device._certfile != None:
      LOG_IOTC("ERROR: micropython client requires the client certificate is embedded.")
      sys.exit()

    response = urequests.request(method, target_url, data=body, headers=headers)
    return response.text
def iot_weather(city_code, data_type):
    if not codey.wifi_is_connected():
        return ''
    res = urequests.request(
        'GET', iot_weather_request_domin + 'getweather?woeid=' +
        str(city_code) + '&type=' + str(data_type))
    text = res.text
    print('=====iot_weather: ' + text)
    if int(data_type) <= 3:
        return int(text)
    return text
Esempio n. 25
0
def http_get(url):
    response = b''
    try:
        r = urequests.request('GET', url)
        response += r.content

    except Exception as ex:
        _logger.error(' Error in http_get ' + str(ex))

    response_str = str(response, 'utf-8')
    # print(response_str)
    return response_str
Esempio n. 26
0
def post_json(endpoint: str, json: str) -> bool:
    try:
        r = request('POST',
                    endpoint,
                    data=json,
                    headers={'Content-Type':
                             'application/json'})  # type:Response
        r.close()
        return 200 <= r.status_code and r.status_code < 300
    except:
        log.error('Failed to post data to PowerBI')
        return False
Esempio n. 27
0
def start_time_entry(time_entry_id):
    post_data = {
        "time_entry": {
            "pid": time_entry_id,
            "created_with": "TimeCube"
        }
    }
    resp = urequests.request('POST',
                             'https://www.toggl.com/api/v8/time_entries/start',
                             json=post_data,
                             headers=auth_header())
    print(resp.content)
Esempio n. 28
0
 def send_tweet(self, text):
     print("LOG: sending tweet: {}".format(text))
     method = "POST"
     url = Twitter.HOST + Twitter.PATH
     data = {'api_key': Twitter.API_KEY, 'status': text}
     data = urlencode(data)
     #headers = { 'X-THINGSPEAKAPIKEY' : Twitter.API_KEY,
     headers = {'Content-Type': 'application/x-www-form-urlencoded'}
     print("LOG: twitter url: {}".format(url))
     resp = requests.request(method, url, headers=headers, data=data)
     print("LOG: Twitter status: {}".format(resp.status_code))
     return
Esempio n. 29
0
    def get_current_weather(self, loc):
        self.loc = loc
        lat = loc["location"]["lat"]
        lon = loc["location"]["lng"]
        path = "weather?lat={}&lon={}".format(lat, lon)
        method = "GET"
        url = OpenWeather.HOST + OpenWeather.CUR_WEA + path + OpenWeather.API_KEY
        print("LOG: getting weather with url: {}".format(url))

        resp = requests.request(method, url)
        print("{} {}".format(resp.status_code, resp.reason))
        self.weather = resp.json()
        return
 def __call__(self, method: str, path: str, data=None) -> requests.Response:
     """Make a call to the Home Assistant API."""
     if data is None:
         data_str = None
     else:
         data_str = json.dumps(data)
     url = self.base_url + path
     if method == METH_GET:
         return requests.get(url, headers=self._headers)
     return requests.request(method,
                             url,
                             data=data_str,
                             headers=self._headers)
Esempio n. 31
0
def get(url):
    resp = urequests.request('GET', url)
    return resp
Esempio n. 32
0
def send(host, port, path='', data='', headers={}):
    url = '%s:%s/%s' % (host, port, path)
    resp = urequests.request('POST', url, json=data, headers=headers)
    return resp