예제 #1
0
    def update_channel(self,
                       pm_1p0=-999,
                       pm_2p5=-999,
                       pm_10p0=-999,
                       temp=-999,
                       hum=-999,
                       out_temp=-999,
                       out_hum=-999,
                       out_pressure=-999):
        _url = format_url(url=Thingspeak.FIELDS_URL,
                          pm_1p0=pm_1p0,
                          pm_2p5=pm_2p5,
                          pm_10p0=pm_10p0,
                          temp=temp,
                          hum=hum,
                          out_temp=out_temp,
                          out_hum=out_hum,
                          out_pressure=out_pressure)
        full_url = Thingspeak.BASE_URL + _url

        # TODO try with context manager
        try:
            urlopen(full_url)
        except Exception as e:
            print(e)
예제 #2
0
def cycle() -> None:
    """Measurement cycle."""
    # Init I2C.
    i2c = machine.I2C(scl=machine.Pin(config.SCL_PIN),
                      sda=machine.Pin(config.SDA_PIN))

    # Init BME280 sensor connected to I2C.
    bme = bme280.BME280(address=config.BME280_I2C_ADDR, i2c=i2c)

    # Read measurements.
    t, p, h = bme.read_compensated_data()
    t, p, h = t / 100, p / 256, h / 1024

    print(t, p, h)

    error = False
    # Sync RTC.
    try:
        ntptime.settime()
    except Exception as err:
        error = True
        log_error('syncing clock', err)

    url = config.URL_TEMPLATE.format(t=t, p=p, h=h)
    try:
        urlopen(url)
    except Exception as err:
        error = True
        log_error('sending metrics', err)

    # Init display.
    display = ssd1306.SSD1306_I2C(DISPLAY_WIDTH,
                                  DISPLAY_HEIGHT,
                                  i2c,
                                  addr=config.DISPLAY_I2C_ADDR)

    display.fill(0)

    # Calculate current time.
    hours = utime.localtime()[3] + config.UTC_OFFSET
    if hours >= 24:
        hours -= 24
    minutes = utime.localtime()[4]
    display.text('{:02d}:{:02d}'.format(hours, minutes), DISPLAY_WIDTH - 40, 2)

    if error:
        display.text('Error', 0, 0)

    # Show measurements.
    display.text('T: {:.2f}C'.format(t), 0, 16)
    display.text('P: {:.2f}hPa'.format(p / 100), 0, 26)
    display.text('H: {:.2f}%'.format(h), 0, 36)

    display.show()
    utime.sleep(5)
    display.poweroff()
예제 #3
0
def get():
	global lasttime
	
	newtime = time.ticks_ms()
	if len(lastjson) < 20 or newtime-lasttime>60000: # nothing read yet or at least one minute pass
		r=urequest.urlopen(url)
		j=ujson.loads(r.read(2000))
		r.close()
		lasttime=newtime
	else:
		j=lastjson
	return j
예제 #4
0
def updatewunderground():
    """ generates the update url """

    url = ''.join([
        'http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?',
        'ID={}'
        '&PASSWORD={}', '&dateutc=now', '&winddir={}', '&windspeedmph={}',
        '&humidity={}', '&dewptf={}', '&tempf={}', '&baromin={}',
        '&soiltempf={}', '&soilmoisture={}', '&action=updateraw'
    ]).format(stationid, stationkey, winddir(), windspeedmph(), humidity(),
              dewptf(), tempf(), baromin(), soiltempf(), soilmoisture())

    try:
        r = request.urlopen(url)
    except Exception as e:
        print('could not send data to wunderground')
        print(e)
예제 #5
0
    def __call__(self, *args):
        buf = uio.StringIO()
        buf.write("<?xml version='1.0'?>\n<methodCall>\n<methodName>")
        buf.write(self.name)
        buf.write("</methodName>\n<params>\n")
        for a in args:
            buf.write("<param><value>")
            if isinstance(a, int):
                buf.write("<int>%s</int>" % a)
            else:
                raise NotImplementedError
            buf.write("</value></param>\n")
        buf.write("</params>\n</methodCall>\n")
        if self.server.verbose:
            print(buf.getvalue())
        body = buf.getvalue().encode()

        f = urlopen(self.server.uri, body, "POST")

        try:
            #print(f.read())
            f = f.makefile()
            tokenizer = xmltok2.tokenize(f)
            xmltok2.gfind(
                tokenizer,
                lambda ev: ev[0] == xmltok2.START_TAG and ev[2] == "value")
            ev = next(tokenizer)
            assert ev[0] == xmltok2.START_TAG
            typ = ev[2]
            ev = next(tokenizer)
            assert ev[0] == xmltok2.TEXT
            val = ev[1]
            if typ == "boolean":
                assert val in ("0", "1")
                return val == "1"
            else:
                assert NotImplementedError
        finally:
            #print("*", f.read())
            f.close()
예제 #6
0
import time
예제 #7
0
def send(form):
    response = request.urlopen(url, data=form)
    print(response.read())
예제 #8
0
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect('TP-LINK_445B', 'jungle00')
        while not sta_if.isconnected():
            pass
    print('network config:', sta_if.ifconfig())
    p0(0)


do_connect()

while True:
    try:
        f = urequest.urlopen(url + 'id/' + str(device_id_1))
        #print ("http get")
        data = f.read()
        data = json.loads(data)
        # port_id_1 = data['id']
        is_change_1 = data['change']
        port_state_1 = data["state"]
        port_type_1 = data['type']

        if device_id_2:
            g = urequest.urlopen(url + 'id/' + str(device_id_2))
            data_2 = g.read()
            data_2 = json.loads(data_2)
            is_change_2 = data_2['change']
            port_state_2 = data_2["state"]
            port_type_2 = data_2['type']
 def _get_data(self):
     request = urlopen(self._url)
     return ujson.load(request)
예제 #10
0
def call_back_2():
    print('call back2')
    state_2 = p5()
    x = urequest.urlopen(url + "cn/" + str(device_id_1) + '/' + str(state_2))
    print("id1 change %s" % state_2)
예제 #11
0
__author__ = 'ebrecht'
예제 #12
0
    import network
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect('TP-LINK_445B', 'jungle00')
        while not sta_if.isconnected():
            pass
    print('network config:', sta_if.ifconfig())
    p0(0)


do_connect()

while True:
    f = urequest.urlopen('http://192.168.10.30:8000/api/id/1')
    print("http get")
    data = f.read()
    data = json.loads(data)
    port_id = data['id']
    is_change = data['change']
    port_state = data["state"]
    port_type = data['type']
    print(port_state)
    if i == 0:
        if port_type == 0:
            print("init out")
            p2 = Pin(2, Pin.OUT)
            p2(port_state)
            i = 1
        else: