Learn, Make and Invent
  • Educational STEM Products
  • Early Primary
    • Bee Bot
    • Ozobot
    • Matatalab Coding Set
    • Neuron coding blocks
    • Osmo ios
    • Cubetto
    • Sphero Bolt
  • Primary
    • Codey Rocky AI Robot
      • Tutorials
        • Introduction
        • Get Started
        • Upload Mode
        • Emotion Blocks
        • IoT Blocks
        • Neuron Blocks
        • IR Remote
        • Use Python
      • Examples
      • Block Reference
        • Looks
        • Lighting
        • Speaker
        • Action
        • Sensing
        • Infrared
        • Events
        • Control
        • Operators
      • Python API Reference
        • Python API for Codey
        • Python API for Rocky
        • Python API for Third-Party Libraries
        • Python API for Neuron Extension Modules
      • FAQs
    • Edison
    • mBot
      • Introduction
      • Building mBot
      • Connect mBot
      • Preset Modes
    • Microbit
    • Merge Cube
    • Bare Conductive Board
    • Tello Edu
  • Secondary
    • Microbit Grove Inventor Kit
    • mBot Ranger
    • Arduino Science Kit
    • Arduino Starter Kit
    • Arduino Grove Starter Kit
    • CoDrone
  • Senior Secondary
    • CoDrone Pro
    • Arduino CTC Go
  • Digital Tech Kits
    • Digital Tech Kit for K-2
    • Digital Tech Kit for 3-5
    • Digital Tech Kit for 6-8
    • Digital Tech Kit for 9-10
  • Makerspace
    • Otto DIY
      • User guide
      • Assembly Instructions
        • Builder Kit
        • Builder Kit +
        • Builder Kit Humanoid
        • Builder Kit E
      • OTTO enclosures 3D and laser cut files
      • Code
    • Curcuitmess
      • Circuitmess Ringo
        • Inside the Box
        • Tools Needed
        • Soldering the parts
        • Assembling the parts
        • Set up your Ringo
  • Grove Ecosystem
    • Grove System
    • Grove Modules
      • Actuators
        • Atom Node
        • Grove 2 Coil Latching Relay
        • Grove Button
        • Grove Buzzer
        • Grove Dry Reed Relay
        • Grove EL Driver
        • Grove Haptic Motor
        • Grove I2C Motor Driver V1.2
        • Grove I2C Motor Driver V1.3
        • Grove I2C Motor Driver
        • Grove LED Matrix Driver v1.0
        • Grove Mini Fan
        • Grove Mini I2C Motor Driver v1.0
        • Grove MP3 v2.0
        • Grove Recorder v3.0
        • Grove Relay
        • Grove Serial MP3 Player
        • Grove Servo
        • Grove Solid State Relay
        • Grove Speaker
        • Grove Variable Color LED
        • Grove Vibration Motor
        • Grove Water Atomization
      • Display
        • Grove 4 Digit Display
        • Grove Circular LED
        • Grove LCD RGB Backlight
        • Grove LED Bar
        • Grove LED Socket Kit
        • Grove LED String Light
        • Grove LED Strip Driver
        • Grove OLED Display 0.96inch
        • Grove OLED Display 1.12inch
        • Grove Red LED
        • I2C LCD
      • Sensors
        • Grove 3 Axis Analog Accelerometer
        • Grove 3 Axis Compass V1.0
        • Grove 3 Axis Digital Accelerometer 1.5g
        • Grove 3 Axis Digital Accelerometer 16g
        • Grove 3 Axis Digital Accelerometer 400g
        • Grove 3 Axis Digital Gyro
        • Grove 6 Axis Accelerometer And Compass V2.0
        • Grove 6 Axis Accelerometer And Gyroscope
        • Grove 80cm Infrared Proximity Sensor
        • Grove Air Quality Sensor v1.3
        • Grove Alcohol Sensor
        • Grove Barometer Sensor BME280
        • Grove Barometer Sensor BMP180
        • Grove Barometer Sensor BMP280
        • Grove Barometer Sensor
        • Grove Barometer High Accuracy
        • Grove Chest Strap Heart Rate Sensor
        • Grove CO2 Sensor
        • Grove Collision Sensor
        • Grove Digital Infrared Temperature Sensor
        • Grove Digital Light Sensor
        • Grove Dust Sensor
        • Grove Ear clip Heart Rate Sensor
        • Grove Electricity Sensor
        • Grove Finger clip Heart Rate Sensor with shell
        • Grove Finger clip Heart Rate Sensor
        • Grove Fingerprint Sensor
        • Grove Gas Sensor O2
        • Grove Gas Sensor
        • Grove HCHO Sensor
        • Grove High Temperature Sensor
        • Grove IMU 10DOF v2.0
        • Grove Infrared Receiver
        • Grove Line Finder
        • Grove Temperature and Humidity Sensor Pro
        • Grove Temperature And Humidity Sensor
        • Grove Voltage Divider
        • Grove Water Sensor
        • Grove XBee Carrier
      • Communication
        • Grove High Precision RTC
        • Grove LoRa Radio
        • Grove NFC Tag
        • Grove NFC
        • Grove 125KHz RFID Reader
        • Grove 315MHz RF Kit
        • Grove 433MHz Simple RF Link Kit
        • Grove Bee Socket
        • Grove BLE v1
        • Grove BLE dual model v1.0
        • Grove DMX512
        • Grove GPS
        • Grove I2C ADC
        • Grove I2C FM Receiver
        • Grove Protoshield
        • Grove RJ45 Adapter
        • Grove Screw Terminal
        • Grove Serial Bluetooth v3.0
        • Grove Serial RF Pro
        • Grove UART Wifi
      • Others
        • Grove Base Booster Pack
        • Grove Base Cape for BeagleBone v2
        • Grove Base HAT
        • Grove Base Shield for NodeMCU V1.0
        • Grove Base Shield for Photon
        • Grove Breakout for LinkIt Smart 7688 Duo
        • Grove Cape for BeagleBone Series
        • Grove Indoor Environment Kit for Edison
        • Grove Inventor Kit for microbit
        • Grove IoT Developer Kit Microsoft Azure Edition
        • Grove IoT Starter Kits Powered by AWS
        • Grove Recorder
        • Grove Shield for Intel Joule
        • Grove Smart Plant Care Kit
        • Grove Speech Recognizer Kit for Arduino
        • Grove Starter Kit for BeagleBone Green
        • Grove Starter Kit for IoT based on Raspberry Pi
        • Grove Starter kit for LinkIt Smart7688 Duo
        • Grove Starter Kit v3
        • Grove AND
        • Grove Base Shield for IOIO OTG
        • Grove BlinkM
        • Grove DC Jack Power
        • Grove Differential Amplifier v1.0
        • Grove Differential Amplifier v1.2
        • Grove GSR Sensor
        • Grove I2C Hub
        • Grove Joint v2.0
        • Grove Mega Shield
        • Grove Mini Camera
        • Grove Mixer Pack V2
        • Grove MOSFET
        • Grove Node
        • Grove NOT
        • Grove NunChuck
        • Grove OR
        • Grove PS 2 Adapter
        • Grove Recorder v2.0
        • Grove Serial Bluetooth
        • Grove Serial LCD V1.0
        • Grove Single Axis Analog Gyro
        • Grove SPDT Relay 30A
        • Grove Starter Kit for LinkIt ONE
        • Grove Starter Kit for mbed
        • Grove Toy Kit
        • Grove Wrapper
        • GrovePi Plus
  • Arduino
    • Graphical coding with Grove sensors
    • Arduino Comparison Sheet
    • Tutorials
      • Setup Arduino Every board in Arduino IDE
      • Arduino Cloud
      • Installing Libraries
      • Motor, Servo for Arduino
      • Sensor for Arduino
    • Examples
      • Genuino 101
        • Prerequisites
        • Shock / Tap Detection
        • LED Control Over Bluetooth
        • Board Orientation Detection
        • Pedometer – Step Counting Over Bluetooth
        • Timer Switch
        • Appendices
          • Appendix A
          • Appendix B
  • micro:bit
    • Examples
      • Servo with micro:bit
  • Halocode
    • Introduction
    • Get Started
    • Upload Mode
    • Speech Recognition
    • User Cloud Message
    • Use Python with HaloCode
    • Code with Mu A Simple Python Editor
      • Examples
        • Basic Project
          • Color Mixer
          • Compare Strength
          • Connect Wi-Fi
          • Control Multiple HaloCodes via LAN
          • Energy Ring
          • Make a Smiling Face with the LED Ring
          • Make a Volume Detector
          • Press the Button to play LED Animation Meteor
          • Rainbow Button
        • Level Up
          • Control HaloCode's LEDs via Voice Command
          • Remote Control
          • Make HaloCode the Steering Wheel of the Car on Stage
          • HaloCode's Remote Control Deck
          • Emotion Detector
          • Deep Learning and Facial Recognition
          • Use Global Variable to Interact with Sprites
        • Workshop
          • A Kitten with Blinking Eyes and a Waving Tail
          • Pedometer
          • Smart Home
  • Troubleshooting
    • Matatalab
      • Matatalab Upgrade
        • Pre Upgrade Instructions - MatataBot
        • MatataBot Upgrade
        • Matata Tower Upgrade
        • Resources for Upgrade
      • Matatalab Pairing
Powered by GitBook
On this page
  • urequests – Network Request Module
  • mqtt – Message Queue Telemetry Transmission

Was this helpful?

  1. Primary
  2. Codey Rocky AI Robot
  3. Python API Reference

Python API for Third-Party Libraries

urequests – Network Request Module

Function

urequests.request(method, url, data=None, json=None, headers={}) Send a network request, it will block the response data returned to the network, parameters:

  • method method of establishing a network request. e.g. HEAD,GET,POST,PUT,PATCH, DELETE.

  • url URL of the network request.

  • data (optional), a dictionary, tuple list [(key, value)] (will be form coded), byte or class file object sent in the request body.

  • json (optional), json data sent in the request body.

  • headers (optional), HTTP header dictionary to be sent with the request.

urequests.head(url, **kw) Send a HEAD request, the return type is the response of the request, parameters:

  • url URL of the network request.

  • **kw request optional parameters.

urequests.get(url, **kw) Send a GET request, the return type is the response of the request, parameters:

  • url URL of the network request.

  • **kw request optional parameters.

urequests.post(url, **kw) Send a POST request, the return type is the response of the request, parameters:

  • url URL of the network request.

  • **kw request optional parameters.

urequests.put(url, **kw) Send a PUT request, the return type is the response of the request, parameters:

  • url URL of the network request.

  • **kw request optional parameters.

urequests.patch(url, **kw) Send a PATCH request, the return type is the response of the request, parameters:

  • url URL of the network request.

  • **kw request optional parameters.

urequests.delete(url, **kw) Send a DELETErequest, the return type is the response of the request, parameters:

  • url URL of the network request.

  • **kw request optional parameters.

Sample Code:

import codey
import urequests as requests
import time

# Fill in your router's ssid and password here.
codey.wifi.start('wifi_ssid', 'password')
codey.led.show(0,0,0)
while True:
    if codey.wifi.is_connected():
        codey.led.show(0,0,255)
        res = requests.get(url='http://www.baidu.com/')
        print(res.text)
        time.sleep(3)
    else:
        codey.led.show(0,0,0)

Sample Code:2

import codey
import urequests as requests
import time

# Fill in your router's ssid and password here.
codey.wifi.start('wifi_ssid', 'password')
codey.led.show(0,0,0)
hour = minite = second = "00"
while True:
    if codey.wifi.is_connected():
        try:
            res = requests.get(url = 'http://www.time.ac.cn/timeflash.asp?user=flash').text
            hour_begin = res.find('<hour>') + len('<hour>')
            hour_end = res.find('</hour>')
            minite_begin = res.find('<minite>') + len('<minite>')
            minite_end = res.find('</minite>')
            second_begin = res.find('<second>') + len('<second>')
            second_end = res.find('</second>')
            if hour_begin > len('<hour>') and hour_end > hour_begin and \
               minite_begin > len('<minite>') and minite_end > minite_begin and \
               second_begin > len('<second>') and second_end > second_begin:

                if hour_end - hour_begin == 1:
                    hour = '0' + res[hour_begin:hour_end]
                elif hour_end - hour_begin == 2:
                    hour = res[hour_begin:hour_end]

                if minite_end - minite_begin == 1:
                    minite = '0' + res[minite_begin:minite_end]
                elif minite_end - minite_begin == 2:
                    minite = res[minite_begin:minite_end]

                if second_end - second_begin == 1:
                    second = '0' + res[second_begin:second_end]
                elif second_end - second_begin == 2:
                    second = res[second_begin:second_end]

                print(hour + ":" + minite + ":" + second)
                cur_time = hour + ':' + minite;
                codey.display.show(cur_time)
        except:
            print("get error data")
    else:
        codey.led.show(0,0,0)

Sample Code:3

import codey
import urequests as requests
import ujson

# user_account and password is mblock's account and password
def get_user_request_header():
    post_data = ujson.dumps({ 'account': 'user_account', 'password': 'password'})
    request_url = 'http://passport2.makeblock.com/v1/user/login'
    res = requests.post(request_url, headers = {'content-type': 'application/json'}, data = post_data).json()
    header_data = ''
    if res['code'] == 0:
        header_data = { "content-type": 'application/json; charset=utf-8', "devicetype": '1'}
        header_data["uid"] = str(res['data']['user']['uid'])
        header_data["deviceid"] = '30AEA427EC60'
    return header_data

# Get weather information
# cid: checkpoint id
# arg: Information to be queried
#            aqi:  Air Quality Index
#            pm25: PM2.5 concentration
#            pm10: PM10 concentration
#            co:   Carbon monoxide concentration
#            so2:  Sulfur dioxide concentration
#            no2:  Nitrogen dioxide concentration
def get_air_quality_info(cid, arg):
    if not codey.wifi.is_connected():
        return ''
    post_data = ujson.dumps({ "cid": cid, "arg": arg})
    request_url = 'http://msapi.passport3.makeblock.com/' + 'air/getone'
    res = requests.post(request_url, headers = get_user_request_header(), data = post_data)
    text = res.text
    return float(text)

# Fill in your router's ssid and password here.
codey.wifi.start('wifi_ssid', 'password')
codey.led.show(0,0,0)
while True:
    if codey.wifi.is_connected():
        codey.led.show(0,0,255)
        data = get_air_quality_info('1539','aqi')  #1539 is Shenzhen checkpoint id
        codey.display.show(data)
    else:
        codey.led.show(0,0,0)

mqtt – Message Queue Telemetry Transmission

Class

class mqtt.MQTTClient(client_id, server, port=0, user=None, password=None, keepalive=0, ssl=False, ssl_params={}) Instantiating the interface object of MQTT client, parameters:

  • client_id the unique client id string used when connecting to the broker. If client_id is zero length or None, then one will be randomly generated. In this case, the parameter clean_session of the connect function must be True.

  • server The host name or IP address of the remote server.

  • port (optional), the network port of the server host to connect to. The default port number is 1883. Please note that the default port number of the MQTT over SSL/TLS is 8833.

  • user (optional), the username registered on the server.

  • password (optional), the password registered on the server.

  • keepalive (optional), the client’s keepalive time out value. Default is 60 s.

  • ssl (optional), whether enable the SSL/TLS support.

  • ssl_params (optional), SSL/TLS parameter.

connect(clean_session=True) Connect the client to the server, this is a blocking function, parameters:

  • clean_session a boolean that determines the client type. If True, the broker will remove all information about this client when it disconnects. If False, the client is a durable client and subscription information and queued messages will be retained when the client disconnects.

reconnect() Reconnect to the server using the details provided previously. You must call connect before calling this function.

disconnect() Disconnect from the server.

ping() Test the connectivity between the server and client.

set_last_will(topic, msg, retain=False, qos=0) Set the will to be sent to the server. If the client disconnects without calling disconnect(), the server will post a message on its behalf, parameters:

  • topic The topic of the will post.

  • msg A will message to send.

  • retain If set to True, the will message will be set to the last known good/reserved message for the topic.

  • qos Is used for the quality of service level of the will.

publish(topic, msg, retain=False, qos=0) A message is sent from the client to the agent and then sent from the agent to any client that subscribes to the matching topic, parameters:

  • topic The topic of the message should be posted.

  • msg The actual message to send.

  • retain If set to True, the will message will be set to the last known good/reserved message for the topic.

  • qos The level of quality of service to use.

subscribe(topic, qos=0) Subscribe to a topic of the service, this module provides some helper functions to subscribe and process messages directly. For example set_callback, parameters:

  • topic The subject of the message to subscribe.

  • qos The level of quality of service to use.

set_callback(f) Sets the callback function for the topic subscription, which is called when the server responds to our subscription request, parameters:

  • f callback function.

wait_msg() Wait for the server until the server has no pending messages. This function is a blocking function.

check_msg() Check if the server has pending messages. If not, return directly, if any, do same processing as function wait_msg.

Sample Code:

from mqtt import MQTTClient
import codey
import time

MQTTHOST = "mq.makeblock.com"
MQTTPORT = 1883

# Fill in as you like
client_id = "20180911203800"

# Example Path
Topic = "/sensors/temperature/#"

mqttClient = MQTTClient(client_id, MQTTHOST, port=MQTTPORT, user='test', password='test', keepalive=0, ssl=False)

# Connect to the MQTT server
def on_mqtt_connect():
    mqttClient.connect()

# publish a message
def on_publish(topic, payload, retain=False, qos = 0):
    mqttClient.publish(topic, payload, retain, qos)

# message processing function
def on_message_come(topic, msg):
    print(topic + " " + ":" + str(msg))
    codey.display.show(msg)

# subscribe message
def on_subscribe():
    mqttClient.set_callback(on_message_come)
    mqttClient.subscribe(Topic, qos = 1)

# Fill in your router's ssid and password here.
codey.wifi.start('wifi_ssid', 'password')
codey.led.show(0,0,0)
codey.display.show(0)
while True:
    if codey.wifi.is_connected():
        on_mqtt_connect()
        on_subscribe()
        codey.led.show(0,0,255)
        while True:
            # Blocking wait for message
            on_publish("/sensors/temperature/home", str(38), qos = 1)
            mqttClient.wait_msg()
            time.sleep(1)
    else:
        codey.led.show(0,0,0)
PreviousPython API for RockyNextPython API for Neuron Extension Modules

Last updated 5 years ago

Was this helpful?