Code Monkey home page Code Monkey logo

adafruit_io_python's Introduction

Adafruit IO Python

Documentation Status Chat Build Status https://img.shields.io/badge/Try%20out-Adafruit%20IO%20Python-579ACA.svg?logo=data:image/png;base64,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

https://cdn-learn.adafruit.com/assets/assets/000/057/153/original/adafruit_io_iopython.png?1530802073

A Python library and examples for use with io.adafruit.com.

Compatible with Python Versions 3.4+

Installation

Easy Installation

If you have PIP installed (typically with apt-get install python-pip on a Debian/Ubuntu-based system) then run:

pip3 install adafruit-io

This will automatically install the Adafruit IO Python client code for your Python scripts to use. You might want to examine the examples folder in this GitHub repository to see examples of usage.

If the above command fails, you may first need to install prerequisites:

pip3 install setuptools
pip3 install wheel

Manual Installation

Clone or download the contents of this repository. Then navigate to the folder in a terminal and run the following command:

python setup.py install

Usage

Documentation for this project is available on the ReadTheDocs.

Contributing

Contributions are welcome! Please read our Code of Conduct before contributing to help this project stay welcoming.

adafruit_io_python's People

Contributors

abachman avatar alfuhrmann avatar barbudor avatar brentru avatar cj8scrambler avatar come-maiz avatar cv65 avatar edzob avatar erickellerek1 avatar flavio-fernandes avatar gblanchard4 avatar jwcooper avatar ladyada avatar lcmcninch avatar mcauser avatar mikeadamz avatar phord avatar pjurek3 avatar radudragusin avatar tdicola avatar tekktrik avatar toddtreece avatar tyeth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adafruit_io_python's Issues

Using the example as-is; no modifications and AIO seems to kick me out every 5 minutes to the second?

Hi,

I am using the Python example mqtt_client.py as-is; no major modifications and AIO seems to kick me out every 5 minutes to the second? I see no time out in the code; am I missing something or is this an AIO issue?

My log is below; with minor fluctuations within a matter of seconds I do get kicked out every 5 minutes; I did modify the exmaple so that it re-connects right away but I though I bring this up.

Thanks

Connected to Adafruit IO!  Listening for festival changes...
Current date & time Tue Aug 30 10:57:43 2016
Disconnected from Adafruit IO!
Current date & time Tue Aug 30 11:02:44 2016
Now we will re-connect to AIO
Connected to Adafruit IO!  Listening for festival changes...
Current date & time Tue Aug 30 11:02:45 2016
Disconnected from Adafruit IO!
Current date & time Tue Aug 30 11:07:45 2016
Now we will re-connect to AIO
Connected to Adafruit IO!  Listening for festival changes...
Current date & time Tue Aug 30 11:07:46 2016
Disconnected from Adafruit IO!
Current date & time Tue Aug 30 11:12:47 2016
Now we will re-connect to AIO
Connected to Adafruit IO!  Listening for festival changes...
Current date & time Tue Aug 30 11:12:48 2016
Disconnected from Adafruit IO!
Current date & time Tue Aug 30 11:17:48 2016
Now we will re-connect to AIO
Connected to Adafruit IO!  Listening for festival changes...
Current date & time Tue Aug 30 11:17:49 2016
Disconnected from Adafruit IO!
Current date & time Tue Aug 30 11:22:50 2016
Now we will re-connect to AIO
Connected to Adafruit IO!  Listening for festival changes...
Current date & time Tue Aug 30 11:22:51 2016
Disconnected from Adafruit IO!
Current date & time Tue Aug 30 11:27:51 2016
Now we will re-connect to AIO
Connected to Adafruit IO!  Listening for festival changes...
Current date & time Tue Aug 30 11:27:52 2016
Disconnected from Adafruit IO!
Current date & time Tue Aug 30 11:32:53 2016

print commands missing parentheses?

I've setup the library on my Raspberry Pi running Arch Linux and Python 3.5.1. When I ran the examples (like mqtt_subscribe.py), I got an error when it came to the first print line:
print 'Connected to Adafruit IO! Listening for {0} changes...'.format(FEED_ID)
it ran fine after changing it like so (for each print in the whole file):
print('Connected to Adafruit IO! Listening for {0} changes...'.format(FEED_ID))

The print lines mentioned in the readme file include the parentheses. Python is not my language so maybe I'm missing something obvious?

Crash on REST API methods: receive_group, receive_next_group

Command: io.receive_group(created_group)

Error Log:

Traceback (most recent call last):
File "", line 1, in
File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 248, in receive_group
return Group.from_dict(self._get(path))
File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 91, in _get
self._handle_error(response)
File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 79, in _handle_error
raise RequestError(response)
Adafruit_IO.errors.RequestError: Adafruit IO request failed: 404 Not Found - not found - API documentation can be found at https://io.adafruit.com/api/docs

Similar issue for next_group:

f = aio.receive_next_group(house_group)
Traceback (most recent call last):
File "", line 1, in
File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 257, in receive_next_group
return Group.from_dict(self._get(path))
File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 91, in _get
self._handle_error(response)
File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 79, in _handle_error
raise RequestError(response)
Adafruit_IO.errors.RequestError: Adafruit IO request failed: 404 Not Found - not found - API documentation can be found at https://io.adafruit.com/api/docs

Expose version #

Presently the library support a call to AdafruitIO.__version__ to check versions, let's make a way to check version #'s of the IO library

MQTT Retained flag not being passed from paho MQTT

The library you're using, paho MQTT, passes a flag 'retain' with each MQTT message. This flag indicates if a message has just arrived, or if it was stored by the server.

http://www.hivemq.com/blog/mqtt-essentials-part-8-retained-messages

class MQTTMessage:
    """ This is a class that describes an incoming message. It is passed to the
    on_message callback as the message parameter.
    Members:
    topic : String. topic that the message was published on.
    payload : String/bytes the message payload.
    qos : Integer. The message Quality of Service 0, 1 or 2.
    retain : Boolean. If true, the message is a retained message and not fresh.
    mid : Integer. The message id.
    """
    def __init__(self):
        self.timestamp = 0
        self.state = mqtt_ms_invalid
        self.dup = False
        self.mid = 0
        self.topic = ""
        self.payload = None
        self.qos = 0
        self.retain = False

This flag is not passed on to the on_message() callback in the io-client-python MQTT client:

    def _mqtt_message(self, client, userdata, msg):
        logger.debug('Client on_message called.')
        # Parse out the feed id and call on_message callback.
        # Assumes topic looks like "username/feeds/id"
        parsed_topic = msg.topic.split('/')
        if self.on_message is not None and self._username == parsed_topic[0]:
            feed = parsed_topic[2]
            payload = '' if msg.payload is None else msg.payload.decode('utf-8')
            self.on_message(self, feed, payload)

Without this flag, there is no way to tell if you're getting a stale message from MQTT when you connect.. You could always ignore the first message after a new client connection, but that is not nearly as elegant as just using this flag.

This is problematic for me because I'm trying to use a feed to trigger software updates. Because MQTT always retains and delivers the last value when you subscribe to a feed, the app would update every single time the MQTT client connects.

Add additional IO Examples for api-v2 release

We should have additional examples in this library which are compatible with API-V2 and based off the recently updated examples within the AIO_Arduino Library: (https://github.com/adafruit/Adafruit_IO_Arduino/tree/master/examples).

Examples involving GPIO (italicized) will support the Raspberry Pi as a target hardware platform.

  • adafruitio_00_publish
  • adafruitio_01_subscribe
  • adafruitio_02_pubsub
  • adafruitio_03_multiple_feeds
  • adafruitio_04_location
  • adafruitio_05_type_conversion
  • adafruitio_06_digital_in
  • adafruitio_07_digital_out
  • adafruitio_08_analog_in
  • adafruitio_09_analog_out
  • adafruitio_10_dashboard_creation
  • adafruitio_11_group_pub
  • adafruitio_12_group_sub
  • adafruitio_13_rgb
  • adafruitio_14_neopixel
  • adafruitio_15_temp_humidity
  • adafruitio_16_servo

disconnect errors not recoverable

I have a publisher only application on an RPi2 that is event based and sends messages infrequently. It sometimes gets disconnected (possibly after inactivity as suggested here although my client runs for hours possibly days before I see the disconnect).

Whatever the cause of the disconnect clients should be able to reconnect, but adding an on_disconnect() callback does not work when there is a connection error as the Adafruit IO library throws a RuntimeError as shown below. Further, this error cannot be caught as it happens in the background thread managing the MQTT communication.

The net effect is that a disconnect when using loop_background() crashes the client.

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/home/pi/tpenv/local/lib/python2.7/site-packages/paho/mqtt/client.py", line 2287, in _thread_main
    self.loop_forever()
  File "/home/pi/tpenv/local/lib/python2.7/site-packages/paho/mqtt/client.py", line 1261, in loop_forever
    rc = self.loop(timeout, max_packets)
  File "/home/pi/tpenv/local/lib/python2.7/site-packages/paho/mqtt/client.py", line 811, in loop
    rc = self.loop_read(max_packets)
  File "/home/pi/tpenv/local/lib/python2.7/site-packages/paho/mqtt/client.py", line 1075, in loop_read
    return self._loop_rc_handle(rc)
  File "/home/pi/tpenv/local/lib/python2.7/site-packages/paho/mqtt/client.py", line 1382, in _loop_rc_handle
    self.on_disconnect(self, self._userdata, rc)
  File "/home/pi/tpenv/local/lib/python2.7/site-packages/Adafruit_IO/mqtt_client.py", line 80, in _mqtt_disconnect
    raise RuntimeError('Unexpected disconnect with rc: {0}'.format(rc))
RuntimeError: Unexpected disconnect with rc: 1

Handle feed 404'ing if the feed does not exist

This library currently 404's (feed not found) when a feed is referenced/assigned in the library, but not yet created:

Traceback (most recent call last):
File "/home/pi/io-client-python/examples/basics/temp_humidity.py", line 46, in
temperature_feed = aio.feeds('temperature')
File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 241, in feeds
return Feed.from_dict(self._get(path))
File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 91, in _get
self._handle_error(response)
File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 79, in _handle_error
raise RequestError(response)
Adafruit_IO.errors.RequestError: Adafruit IO request failed: 404 Not Found - not found - API documentation can be found at https://io.adafruit.com/api/docs

We should check against the list of feeds to see if the feed exists. If it does not exist, create the feed.

I feel the best place to add this functionality is within client.py's feeds method, changing the functionality from:

    """Retrieve a list of all feeds, or the specified feed.  If feed is not
    specified a list of all feeds will be returned.  If feed is specified it
    can be a feed name, key, or ID and the requested feed will be returned.
    """

to

    """Retrieve a list of all feeds, or the specified feed.  If feed is not
    specified a list of all feeds will be returned.  If feed is specified,
     we'll check if the feed exists and the requeusted feed will be returned. 
     If the feed does not exist, we'll call create_feed to create the specified feed.
    """

Add receive method for MQTT

While mqtt is pub/sub and not request/response, there's a trick we've added into the Adafruit IO MQTT Client which allows you to get the most recent value of a feed.

If you are subbed to username/feeds/key and publish to username/feeds/key/get then IO will send the most recent value to the client on the original subscription. The important fact is that username/feeds/key should be the same for both (you can't have one use feed.key and one use feed.name)

We've exposed this functionality in Adafruit IO Arduino, but should add it into Adafruit IO Python too

AIO API currently returns 422 when throttled, not 429

https://github.com/adafruit/io-client-python/blob/75a84c56c23235e76a99305284dccc4bf900a021/Adafruit_IO/client.py#L64

The client is checking for a 429 specifically, but I am being throttled and the HTTP status code being raised to the caller is a 422/Unprocessable Entity. Is the AIO web server returning the incorrect status code right now or is it correct and Client() should be raising your ThrottlingError exception class?

The 429 is the correct status to be sending back to my client, but I'm not sure which side of this is 'wrong'.

Disconnected function not being called in MQTT client

My code is slightly modified from the example:

https://gist.github.com/mikeadamz/024abb04a8092c9cac61

But when I get disconnected, instead of exiting I get this:

Publishing 71.6 to GarageTemp.
Publishing 71.6 to GarageTemp.
Publishing 71.6 to GarageTemp.
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2287, in _thread_main
    self.loop_forever()
  File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1261, in loop_forever
    rc = self.loop(timeout, max_packets)
  File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 811, in loop
    rc = self.loop_read(max_packets)
  File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1075, in loop_read
    return self._loop_rc_handle(rc)
  File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1382, in _loop_rc_handle
    self.on_disconnect(self, self._userdata, rc)
  File "/usr/local/lib/python2.7/dist-packages/Adafruit_IO/mqtt_client.py", line 80, in _mqtt_disconnect
    raise RuntimeError('Unexpected disconnect with rc: {0}'.format(rc))
RuntimeError: Unexpected disconnect with rc: 1

Publishing 71.6 to GarageTemp.
Publishing 71.6 to GarageTemp.
Publishing 71.4866 to GarageTemp.

As you can see; no exit and the loop keeps running. The only problem is that any loop iteration after the RunTime error does not make it to Adafruit IO

Update API paths to /api/v1

This is needed to make sure that older versions of the lib will work when we make breaking changes with API v2.

Can't import Adafruit_IO -- ImportError: cannot import name MQTTClient

Traceback (most recent call last):
File "./mqtt.py", line 9, in
from Adafruit_IO import MQTTClient
File "/usr/local/lib/python2.7/dist-packages/Adafruit_IO/init.py", line 21, in
from .client import Client
File "/usr/local/lib/python2.7/dist-packages/Adafruit_IO/client.py", line 23, in
import requests
File "/usr/lib/python2.7/dist-packages/requests/init.py", line 80, in
from . import utils
File "/usr/lib/python2.7/dist-packages/requests/utils.py", line 25, in
from .compat import parse_http_list as _parse_list_header
File "/usr/lib/python2.7/dist-packages/requests/compat.py", line 91, in
import cookielib
File "/usr/lib/python2.7/cookielib.py", line 32, in
import re, urlparse, copy, time, urllib
File "/home/chip/copy.py", line 9, in
from Adafruit_IO import MQTTClient
ImportError: cannot import name MQTTClient

api-v2: only send values that are explicitly set when creating new models

See example below, the only values that should be sent are "name" and "key" below. The others should not be set.

Defaults are set in model.py:
Feed.__new__.__defaults__ = tuple(None for x in FEED_FIELDS)

from Adafruit_IO import Client, Feed
feed = Feed(name="June Python", key="june-python")
feed
Feed(name='June Python', key='june-python', description=None, unit_type=None, unit_symbol=None, history=None, visibility=None, license=None, status_notify=None, status_timeout=None)

MQTT retain and /get functionality

I was hoping to use the functionality described here

What I am trying to do is to be able to return all the DATA_FIELDS from the most recent feed entry, I want to use either the created_epoch or created_at field to be able to see if my 2 (soon to be 6) IO clients have stopped uploading, they normally upload every minute.

Example

from Adafruit_IO import Client
aio = Client('USER NAME', 'IO KEY')

feed1 = aio.feeds('freezer5')
feed2 = aio.feeds('freezer6')

# Print out the metadata of last retained entry.
print("Freezer5: "+str(feed1.get()))
print("\nFreezer6: "+str(feed2.get()))

Would output the last retained entry from each feed:
Freezer5: Data(created_epoch=1537685617, created_at='2018-09-23T06:53:37Z', updated_at=None, value='5.899999999999999', completed_at=None, feed_id=869316, expiration='2018-10-23T06:53:37Z', position=None, id='0DZGT0SPKF92RADE5FQ20W3GN7', lat=None, lon=None, ele=None)
Freezer6: Data(created_epoch=1537685676, created_at='2018-09-23T06:53:36Z', updated_at=None, value='6.350000000000001', completed_at=None, feed_id=869316, expiration='2018-10-23T06:53:36Z', position=None, id='0DZGT1BJ2S2VDS7ZAP5N0SGBPN', lat=None, lon=None, ele=None)

location example fails if feed does not exist

the example in api/location.py failed if the requested feed does not exist:
it works if the feed is already there.
I created a feed named 'location' and the script worked fine.
I changed the requested feed to "newlocation" and it failed as below:

I am running this on a Raspberry Pi using adafruit-io v2.0.9

pi@gjnpi3p-1:~/projects/adafruitio/examples/api $ python3 location.py 
Traceback (most recent call last):
  File "location.py", line 23, in <module>
    location = aio.feeds('newlocation')
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 223, in feeds
    return Feed.from_dict(self._get(path))
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 88, in _get
    self._handle_error(response)
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 76, in _handle_error
    raise RequestError(response)
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/errors.py", line 40, in __init__
    error_message = self._parse_error(response)
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/errors.py", line 46, in _parse_error
    content = json.loads(response.content)
  File "/usr/lib/python3.5/json/__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

key check in mqtt_client.py

Copied from: https://github.com/adafruit/io-issues/issues/6

Low priority but in mqtt_client.py, class MQTTClient, def init the key is a very important parameter. New folks could omit it, use "Insert Key Here", or other nonsense. Suggest that in init any testing of the key be done to throw an error rather than get further into the code where it might not be more obvious.

Connecting with SSL/TLS

Is it possible to connect securely using SSL/TLS like in this post? As far as I can see this package uses an insecure MQTT client on port 1883.

mqtt publish and REST send not working

Hi there,

I am able to subscribe to changes on an feed without issue, however publish does not seem to be working. I am not getting an error message but no new data is showing up on adafruit.io.

I am also not able to send data with the REST examples. I just get back the following:

>>> aio.send('test', 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/Adafruit_IO/client.py", line 90, in send
    return Data.from_dict(self._post(path, {'value': value}))
  File "/usr/local/lib/python2.7/dist-packages/Adafruit_IO/client.py", line 72, in _post
    self._handle_error(response)
  File "/usr/local/lib/python2.7/dist-packages/Adafruit_IO/client.py", line 56, in _handle_error
    raise RequestError(response)
Adafruit_IO.errors.RequestError: Adafruit IO request failed: 500 Internal Server Error

I am running this on a Raspberry Pi 2 with Python 2.7

Any thoughts as to what might be going on?

No module named Adafruit_IO

i have installed and used the line

from Adafruit_IO import Client

but im getting an error as

pi@raspberrypi:~ $ python ser-read-ada2.py
Traceback (most recent call last):
File "ser-read-ada2.py", line 4, in
from Adafruit_IO import Client
ImportError: No module named Adafruit_IO

Add Adafruit IO's Random Data Service

Add access to Adafruit IO's Random Data service for both REST and MQTT clients.

About the Adafruit IO Random Service:

Create random data streams that can generate colors, words, numbers, or pick a value from a custom data set and send it directly to your devices.

The four available data types are:

Pronounceable nonsense words
Colors (RGB values, HSL values, CSS hex, or CSS color name)
Numbers
Preset (sample from a given set of values)
Data randomizes once per minute, so multiple streams using the same seed value will get the same random value, even across user accounts.

You can have up to 20 active randomized word services.

Add Group Subscribe/Publish MQTT_Client

Add the ability to subscribe to a group and publish to feeds within a group.
{username}/groups/{group_key}

Sample group response, in csv

$feed-key,$value
$feed-key,$value
location,$lat,$lon,$ele

In MQTTClient, unable to connect via client.connect()

Thank you for opening an issue on an Adafruit Python library repository. To
improve the speed of resolution please review the following guidelines and
common troubleshooting steps below before creating the issue:

  • Do not use GitHub issues for troubleshooting projects and issues. Instead use
    the forums at http://forums.adafruit.com to ask questions and troubleshoot why
    something isn't working as expected. In many cases the problem is a common issue
    that you will more quickly receive help from the forum community. GitHub issues
    are meant for known defects in the code. If you don't know if there is a defect
    in the code then start with troubleshooting on the forum first.

  • If following a tutorial or guide be sure you didn't miss a step. Carefully
    check all of the steps and commands to run have been followed. Consult the
    forum if you're unsure or have questions about steps in a guide/tutorial.

  • For Python/Raspberry Pi projects check these very common issues to ensure they don't apply:

    • If you are receiving an ImportError: No module named... error then a
      library the code depends on is not installed. Check the tutorial/guide or
      README to ensure you have installed the necessary libraries. Usually the
      missing library can be installed with the pip tool, but check the tutorial/guide
      for the exact command.

    • Be sure you are supplying adequate power to the board. Check the specs of
      your board and power in an external power supply. In many cases just
      plugging a board into your computer is not enough to power it and other
      peripherals.

    • Double check all soldering joints and connections. Flakey connections
      cause many mysterious problems. See the guide to excellent soldering for examples of good solder joints.

If you're sure this issue is a defect in the code and checked the steps above
please fill in the following fields to provide enough troubleshooting information.
You may delete the guideline and text above to just leave the following details:

  • Platform/operating system (i.e. Raspberry Pi with Raspbian operating system,
    Windows 32-bit, Windows 64-bit, Mac OSX 64-bit, etc.): INSERT PLATFORM/OPERATING
    SYSTEM HERE

  • Python version (run python -version or python3 -version): INSERT PYTHON
    VERSION HERE

  • Error message you are receiving, including any Python exception traces: INSERT
    ERROR MESAGE/EXCEPTION TRACES HERE
    *

  • List the steps to reproduce the problem below (if possible attach code or commands
    to run): LIST REPRO STEPS BELOW

Add more verbose error messages

Hit an error today while using this library while sending data to a feed before the feed was created:

Adafruit_IO.errors.RequestError: Adafruit IO request failed: 404 Not Found - n - o - t - - f - o - u - n - d - - - - - A - P - I - - d - o - c - u - m - e - n - t - a - t - i - o - n - - c - a - n - - b - e - - f - o - u - n - d - - a - t - - h - t - t - p - s - : - / - / - i - o - . - a - d - a - f - r - u - i - t - . - c - o - m - / - a - p - i - / - d - o - c - s

The current error handling only throws a descriptive exception when you hit a throttling error: (https://github.com/adafruit/io-client-python/blob/master/Adafruit_IO/errors.py#L21)

But there are a lot of errors which can be thrown by the API within (https://github.com/adafruit/io-client-python/blob/master/Adafruit_IO/errors.py#L21).

Allow user to override keepalive

Users cannot override keepalive argument on connect() method:

File "fridgecam.py", line 74, in mqtt_run
    aio_mqtt.connect(keepalive=60)
  File "/usr/local/lib/python3.4/dist-packages/Adafruit_IO/mqtt_client.py", line 107, in connect
    keepalive=KEEP_ALIVE_SEC, **kwargs)
TypeError: connect() got multiple values for keyword argument 'keepalive'

I will submit a pull request shortly.

python library receive() returns 400 Bad Request instead of 404 Not Found

OS: Windows 64-bit
Python Version: Python 2.7.12
Traceback (most recent call last):

  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\Adafruit_IO\client.py", line 106, in receive
    return Data.from_dict(self._get(path))
  File "C:\Python27\lib\site-packages\Adafruit_IO\client.py", line 63, in _get
    self._handle_error(response)
  File "C:\Python27\lib\site-packages\Adafruit_IO\client.py", line 56, in _handle_error
    raise RequestError(response)
Adafruit_IO.errors.RequestError: Adafruit IO request failed: 400 Bad Request

Description:
I've been playing around with the Adafruit IO python library. When testing out the Feed receive() method, I was mislead by an HTTP status code that was returned in the traceback.

As you can see in the output above, I got a 400 Bad Request status in response to calling receive() which initially lead me to believe there must be a bug in the python library as it should not be sending malformed requests to your API. A 400 status code should mean that the request is malformed, not that the resource doesn't exist.

It turned out that I had a typo in my feed name and so the problem was simply the feed I was trying to read from did not exist, but this error caused me to waste time debugging the library instead.

My suggestion is to return a 404 in the event that someone attempts to access a feed that does not exist. This would more closely follow standard REST practices.

Reproduction Steps:

  • Initialize client with a valid key
  • Try to read a feed that doesn't exist. i.e. client.receive('non-existing-feed')

Sample Reproduction Code:

from Adafruit_IO import Client
client = Client('#######')
client.receive('non-existing-feed')

Update:

I should note that after I ran into this, I initially thought to report this as a bug with the API but I couldn't reproduce using the REST API console at https://io.adafruit.com.

Trying https://io.adafruit.com/api/docs/#!/Data/all it appears that the API is returning a 404 if I try to read all data from a feed that doesn't exist.

If I try https://io.adafruit.com/api/docs/#!/Data/receive with a non-existing feed name, I get a 200 OK which is also odd. I'm not sure why the python library receive call is getting a 400.

So at this point it seems specific to the python client, but is probably an API problem somewhere.

Should I ignore the ZeroReturnError?

This does not always happen, should I just ignore this and continue?

OpenSSL.SSL.ZeroReturnError
Traceback (most recent call last):
File "./sensor.py", line 51, in presenseHandle
securityEnable = restClient.receive('Security')
File "build/bdist.linux-armv6l/egg/Adafruit_IO/client.py", line 106, in receive
File "build/bdist.linux-armv6l/egg/Adafruit_IO/client.py", line 62, in _get
File "/usr/lib/python2.7/dist-packages/requests/api.py", line 60, in get
return request('get', url, *_kwargs)
File "/usr/lib/python2.7/dist-packages/requests/api.py", line 49, in request
return session.request(method=method, url=url, *_kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 457, in request
resp = self.send(prep, *_send_kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 606, in send
r.content
File "/usr/lib/python2.7/dist-packages/requests/models.py", line 724, in content
self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
File "/usr/lib/python2.7/dist-packages/requests/models.py", line 653, in generate
for chunk in self.raw.stream(chunk_size, decode_content=True):
File "/usr/lib/python2.7/dist-packages/urllib3/response.py", line 256, in stream
data = self.read(amt=amt, decode_content=decode_content)
File "/usr/lib/python2.7/dist-packages/urllib3/response.py", line 186, in read
data = self._fp.read(amt)
File "/usr/lib/python2.7/httplib.py", line 573, in read
s = self.fp.read(amt)
File "/usr/lib/python2.7/socket.py", line 380, in read
data = self._sock.recv(left)
File "/usr/lib/python2.7/dist-packages/urllib3/contrib/pyopenssl.py", line 188, in recv
data = self.connection.recv(_args, **kwargs)

Import error : No module named Adafruit_IO

i am trying to run python program in raspberrypi3. but it gives following error.
python3 seasonal_2_streetlight_vinz.py
Traceback (most recent call last):
File "seasonal_2_streetlight_vinz.py", line 4, in
from Adafruit_IO import MQTTClient
ModuleNotFoundError: No module named 'Adafruit_IO'

i am also install python 3.6 and run this python code but getting same output.
please help me !

simple.py example fails

with adafruit-io 2.0.9 I get the following error for the example in api/simple.py

The error occurs even when the Feed exists

pi@gjnpi3p-1:~/projects/adafruitio/examples/api $ python3 simple.py 
Traceback (most recent call last):
  File "simple.py", line 21, in <module>
    aio.send_data('Test', 42)
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 117, in send_data
    return self.create_data(feed, Data(value=value))
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 203, in create_data
    return Data.from_dict(self._post(path, data._asdict()))
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 100, in _post
    self._handle_error(response)
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/client.py", line 76, in _handle_error
    raise RequestError(response)
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/errors.py", line 40, in __init__
    error_message = self._parse_error(response)
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_IO/errors.py", line 46, in _parse_error
    content = json.loads(response.content)
  File "/usr/lib/python3.5/json/__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

Docs on Readthedocs not up to date

Hey,

I was just checking out the adafruit-io client and it seems that the documentation on Readthedocs is not up to date with master/io-client-python/docs/quickstart.rst.

Thanks for having a look into it :)

Exceeded the limit of Adafruit IO requests

im using this librarys send function to feed my data to my Adafruit.io feeds
and im using a 10sec delay inside the loop but it says

"Adafruit_IO.errors.ThrottlingError: Exceeded the limit of Adafruit IO requests in a short period of time. Please reduce the rate of requests and try again later."

why it happens with 10 sec delay and How can i fix it?

heres my code i was trying

import serial
import RPi.GPIO as GPIO
import os, time
# Import Adafruit IO REST client.
from Adafruit_IO import Client

GPIO.setmode(GPIO.BOARD)
port = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=2)

# Set to your Adafruit IO key.
ADAFRUIT_IO_KEY = ''
aio = Client(ADAFRUIT_IO_KEY)   # port.write('A')

# Create an instance of the REST client.

# Send a value to the feed 'Test'.  This will create the feed if it doesn't
# exist already.

while True:
        rcv = port.readline(10)



        val = int(rcv)
        print val
        time.sleep(2)
        aio.send('Light', val)
        time.sleep(10)

Adafruit MQTT not connecting

Hi,

I have modified the mqtt_client.py to subscribe to my own feed on Adafruit.io. Sometimes it would work without a problem, but at the moment when I run the script, it literally prints out nothing, I am not sure if it even successfully being connected to the server. I actually encountered this problem a couple months back, but at the moment I am working on a project where I need it to connect successfully at all time.

I am a very very begineer python user and have been programming in C++ the whole time, so I might have miss something obvious. I have uploaded the code, but I only changed three lines which are subscribing to my own feed, and setting the Adafruit id and user name.

Would someone be able to give me some pointers on what went wrong? At the moment, Adafruit IO only allows 2 requests per second. Could it be I might have accidentally exceed the limit, and temporary banned from the server?

Thank you for your time in advance.

Break out errors into explicit types

In particular break out connection attempt failed errors (non-zero RC in connect callback), and the disconnect errors (non-zero RC in disconnect callback) into explicit error types that inherit from a common error base. This way it's easier to catch errors like unexpected disconnects and retry connecting to the service.

Poor error message for feed limit reached

If you attempt the following, when you have hit the maximum number of feeds allowed on your account:

aio.send('oneFeedTooMany', 6)

You get a generic error "Adafruit_IO.errors.RequestError: Adafruit IO request failed: 422 Unprocessable Entity".

This lost an hour while I attempted to debug it. Need a better error message if possible in the Python lib.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.