Exemple #1
0
def _run_request_with_retry(url, body, headers):
    retry = 0
    r = None
    logger = logging.getLogger("log")

    while retry < 10:
        gc.collect()
        try:
            logger.debug("Trying to send...")
            r = requests.post(url, data=body, headers=headers)

            if r.status_code != 200:
                raise CustomVisionError(r.text)
            break
        except RuntimeError as runtime_error:
            logger.info("Could not send data, retrying after 5 seconds: " +
                        str(runtime_error))
            retry = retry + 1

            if retry >= 10:
                raise

            time.sleep(0.5)
            continue

    gc.collect()
    return r
Exemple #2
0
 def ha_request(self, method, path, data = ''):
     headers = {
         'Authorization': 'Bearer ' + self.access_token,
         'Content-Type': 'application/json',
     }
     if method == "POST":
         response = requests.post(self.url + path, data = data, headers = headers)
     elif method == "GET":
         response = requests.get(self.url + path, headers = headers)
     return response
def test_post_string():
    mocket.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), )
    sock = mocket.Mocket(HEADERS + ENCODED)
    mocket.socket.return_value = sock

    adafruit_requests.set_socket(mocket, mocket.interface)
    data = "31F"
    response = adafruit_requests.post("http://" + HOST + "/post", data=data)
    sock.connect.assert_called_once_with((IP, 80))
    sock.send.assert_called_with(b"31F")
    response.close()
def test_post_string():
    mocket.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), )
    sock = mocket.Mocket(headers + encoded)
    mocket.socket.return_value = sock

    adafruit_requests.set_socket(mocket, mocket.interface)
    data = "31F"
    r = adafruit_requests.post("http://" + host + "/post", data=data)
    sock.connect.assert_called_once_with((ip, 80))
    sock.send.assert_called_with(b"31F")
    r.close()
Exemple #5
0
def post_data(CUSTOMER):
    print("Posting value:", CUSTOMER)
    json_data = {'private_key':PRIVATE_KEY, 
        'sensor':SENSOR_ID, 
        'value':CUSTOMER
    } 
    print("Posting to ",JSON_POST_URL)

    response = requests.post(JSON_POST_URL, json=json_data)
    print(response.content)
    response.close()
    print("posted!")
Exemple #6
0
    def _do_call(self, url_suffix=None, soapaction=None, body=None):
        """Main method performaing the SOAP action.

        Keyword Arguments:
            url_suffix {string} -- Command suffix for the url (default: {None})
            soapaction {string} -- SOAP header fields (default: {None})
            body {string} -- SOAP body (default: {None})

        Returns:
            string -- raw status text
        """
        gc.collect()
        url = f"{FritzboxStatus.fritz_url_base}{url_suffix}"
        headers = FritzboxStatus.fritz_headers.copy()
        headers["soapaction"] = soapaction

        try:
            gc.collect()
            response = requests.post(url,
                                     data=body,
                                     headers=headers,
                                     timeout=2)
            gc.collect()
        except MemoryError:
            supervisor.reload()
        except:
            self.log("Couldn't get DSL status, will try again later.")
            return "Unknown"  # We just ignore this and wait for the next request

        # Finde the raw status based on the respective XML Tags
        if url_suffix == "WANIPConn1":
            regex = r"<NewConnectionStatus>(.*)<\/NewConnectionStatus>"
        else:
            regex = r"<NewPhysicalLinkStatus>(.*)<\/NewPhysicalLinkStatus>"

        matches = re.search(regex, response.text)
        status = matches.groups()[0]

        self.log(f"Received DSL state for {url_suffix}: {status}")

        # Clean Up
        response = None
        regex = None
        matches = None
        gc.collect()

        return status
    def post(self, url, **kw):
        """
        Pass the Post request to requests and update status LED

        :param str url: The URL to post data to
        :param dict data: (Optional) Form data to submit
        :param dict json: (Optional) JSON data to submit. (Data must be None)
        :param dict header: (Optional) Header data to include
        :param bool stream: (Optional) Whether to stream the Response
        :return: The response from the request
        :rtype: Response
        """
        if not self.is_connected:
            self.connect()
        self.pixel_status((0, 0, 100))
        return_val = requests.post(url, **kw)
        return return_val
Exemple #8
0
    index = index + 1

    if packet is not None:
        try:
            pt = str(packet, 'ascii')
            print("Received: ", pt)
            pl = pt.strip().split(',')
            if len(pl) == 3:
                temp = pl[0]
                pressure = pl[1]
                depth = pl[2]

                json_data = {
                    "temp": temp,
                    "pressure": pressure,
                    "depth": depth
                }

                print("Posting to ", JSON_POST_URL)

                response = requests.post(JSON_POST_URL, json=json_data)
                #print(response.content)

                response.close()

                print("Done. Sleeping for 90 sec")
                time.sleep(90)

        except Exception as e:
            print("error: " + str(e))
    print("Connecting to network...")
    network.connect()
    time.sleep(0.5)
print("Network Connected!")

# Initialize a requests object with a socket and cellular interface
requests.set_socket(cellular_socket, fona)

counter = 0

while True:
    print("Posting data...", end="")
    data = counter
    feed = "test"
    payload = {"value": data}
    response = requests.post(
        "http://io.adafruit.com/api/v2/"
        + secrets["aio_username"]
        + "/feeds/"
        + feed
        + "/data",
        json=payload,
        headers={"X-AIO-KEY": secrets["aio_key"]},
    )
    print(response.json())
    response.close()
    counter = counter + 1
    print("OK")
    response = None
    time.sleep(15)
        continue

print("Wi-Fi connected to", str(esp.ssid, "utf-8"))
print("IP address", esp.pretty_ip(esp.ip_address))


# Initialize HTTP POST client
adafruit_requests.set_socket(adafruit_esp32spi_socket, esp)


try:
    # Some test data
    humidity = 55
    temperature = 25

    # Setup server url
    post_url = "https://" + TS_HTTP_SERVER + "/update"
    # Create payload
    payload = "api_key=" + TS_WRITE_API_KEY + "&field1=" + \
        str(temperature) + "&field2=" + str(humidity)

    # Send a single message
    response = adafruit_requests.post(post_url, data=payload)

    # Print the http status code; should be 200
    print(response.status_code)

    response.close()
except RuntimeError as error:
    print(error)
Exemple #11
0
                json_data.update({'rssi': rfm9x.rssi})
                #json_data=json_data+"}"
                print(json_data)
                #temp = parts[1]
                #print("temp=",temp)

                #json_data = {"cpu_temperature":temp}
                #json_data = p

                #json_data = {"cpu_temperature":32.2}
                print("json_data:", json_data)

                print("Posting to ", EDGE_POST_URL)

                connect(WIFI_ESSID, WIFI_PASS)
                response = requests.post(EDGE_POST_URL, json=json_data)
                response.close()

                print("Done. Sleeping for ", SLEEP_TIME, "seconds")

                for i in range(0, 3):
                    led.value = True
                    time.sleep(.1)
                    led.value = False

                time.sleep(SLEEP_TIME)  #in case no timer

    except Exception as e:
        if (attemptCount > MAX_ATTEMPTS):
            print("Error -- will try again in ", SLEEP_TIME, "seconds")
            time.sleep(SLEEP_TIME)  #in case no timer
Exemple #12
0
JSON_POST_URL = "http://tspann-mbp15-hw14277:9989/pyportal"

# Set up ADT7410 sensor
i2c_bus = busio.I2C(board.SCL, board.SDA)
adt = adafruit_adt7410.ADT7410(i2c_bus, address=0x48)
adt.high_resolution = True

# Set up an analog light sensor on the PyPortal
adc = AnalogIn(board.LIGHT)

while True:
    try:
        light_value = adc.value
        print('Light Level: ', light_value)
        temperature = adt.temperature
        print('Temperature: %0.2f C' % (temperature))
        data = {"light": light_value, "temperature": temperature}
        response = requests.post(JSON_POST_URL, data=data)
        json_resp = response.json()
        # Parse out the 'data' key from json_resp dict.
        print("Data received from server:", json_resp['data'])
        print('-' * 40)
        response.close()

    except (ValueError, RuntimeError) as e:
        print("Failed to get data, retrying\n", e)
        wifi.reset()
        continue
    print('Delaying {0} seconds...'.format(IO_DELAY))
    time.sleep(IO_DELAY)
        print('WHAM')
        time.sleep(1)
    if x.value < 40000:
        dot[0] = [0, 255, 0]
    if h == 2:
        dot[0] = [100, 255, 0]
    elif h == 3:
        dot[0] = [200, 200, 0]
    elif h == 4:
        dot[0] = [255, 100, 0]
    elif h >= 5:
        dot[0] = [255, 0, 0]
        time.sleep(2)
        print('pull player')

    try:
        n = requests.post("http://608dev.net/sandbox/mostec/helmet?hits=300")
        r = requests.get("http://608dev.net/sandbox/mostec/helmet?hits")
        first = r.text.split(":")
        second = first[1].split(",")
        third = second[0].split("'")
        s = third[1]
        b = (int(s))
    except Exception as e:
        print(e)

    print((x.value, y.value, z.value))
    print(h)
    print(b)
    time.sleep(0.05)