kintone+pico_W

import urequests as requests

import network

import machine

import utime

from machine import Pin



#############################################   WIFI SETUP    ###################################################

#link to local wifi

ssid = "SSID" #WiFi name

password = "PASSWORD" #WiFi Password

wlan = network.WLAN(network.STA_IF)

wlan.active(True)

wlan.connect(ssid, password)


#Wait for connect or fail

max_wait = 10

while max_wait > 0:

    if wlan.status() < 0 or wlan.status() >= 3:

        break

    max_wait -= 1

    print("waiting for connection...")

    utime.sleep(1)


#Handle connection error

if wlan.status() != 3:

    raise RuntimeError('network connection failed')

else:

    print('connected')

    status = wlan.ifconfig()

    print('ip = ' + status[0])

    

 


led = machine.Pin("LED", machine.Pin.OUT)



#############################################  GET TEMPERAUTRE    ###################################################

def gettemp():

    sensor_temp = machine.ADC(4)

    conversion_factor = 3.3 / (65535)

    reading = sensor_temp.read_u16() * conversion_factor 

    temperature = 27 - (reading - 0.706)/0.001721    

    return temperature


def getavetemp(time = 5):

    t = 0

    stack = []

    while t < 3:

        cur_temp = gettemp()

        stack.append(cur_temp)

        utime.sleep(time)

        t += 1

#        print(stack)

    tempsum = sum(stack)

    avetemp = sum(stack) / len(stack)

    return avetemp


#############################################  KINTONE API    ###################################################

  

api_token = "API_TOKEN"  #


URL = "https://kakoki.cybozu.com:443" # URL

APP_ID = "110" # kintoneのアプリID

API_TOKEN = api_token # kintoneのAPIトークン





class KINTONE:

    def PostToKintone(self, url, appId, apiToken, record):

        #KINTONE field code: Text1

        record= record #書き込むフィールドコードとデータ

        data = {'app':appId,'record':record}

        headers = {"X-Cybozu-API-Token": apiToken, "Content-Type" : "application/json"}

        resp=requests.post(url+'/k/v1/record.json',json=data,headers=headers)


        return resp



#if __name__ == '__main__':



#    print resp.text

#############################################  KINTONE API    ###################################################


while True:

    try:

        avetemp = getavetemp(time = 1)

        record = {'TEMP':{'value' : avetemp}}

        knt=KINTONE()

        resp=knt.PostToKintone(URL, APP_ID, API_TOKEN, record)

        resp.close()  #Important 

"""

You must close the returned response object after making a request using the urequests library using response.close(). If you do not, the object will not be garbage-collected, and if the request is being made inside a loop this will quickly lead to a crash. 

"""     

    except:

        utime.sleep(1)

        print("error")

        continue