Giter Site home page Giter Site logo

ibm-watson-iot / iot-python Goto Github PK

View Code? Open in Web Editor NEW
187.0 64.0 202.0 5.28 MB

Python Package and samples for connecting to Maximo IoT and IBM Watson IoT Platform

Home Page: http://ibm-watson-iot.github.io/iot-python/

License: Eclipse Public License 1.0

Python 99.84% Shell 0.12% Makefile 0.05%
sdk python iot

iot-python's People

Contributors

amitmangalvedkar avatar amprasanna avatar angelodanducci avatar benbakowski avatar cclauss avatar dtclarke avatar durera avatar dwc1 avatar ehsanmasdar avatar fidaaalsubhat avatar hnorlen avatar hrhrprasath avatar ianboden avatar ind1go avatar istrate avatar jeffdare avatar johnwalicki avatar jonahluckett avatar milad-laly avatar mkilivan avatar msmiths avatar phariprasadreddy avatar sanjayprab avatar sathipal avatar slaupster avatar stonepd avatar timjacobi avatar vikkipaterson avatar whitfiea 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  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

iot-python's Issues

historian.py should be removed

As historian was sunset as service from Watson IoT Platform is should be removed as well from here. (the code and the sample)

Gateway management threads not cleaned up

threading.Timer(lifetime-120, self.manage, [lifetime, supportDeviceActions, supportFirmwareActions]).start()

A new thread is started when a manage event is received (via threading.Timer), which is never joined/cancelled. This in turn starts a new thread without cancelling/joining the old thread, etc. This means that after running for a few days we're getting OS errors because our process has hundreds of threads and can't create any more.

Python Cli get device list only return 25 devices, possible pagination?

Hi when I run the below script to get a list of all devices in IoT Foundation, I only can get up to 25 devices

[me@localhost ~]$ python cli.py -c app-production.cfg device list
d:hld45t:test:001                       Registered 14 days ago by [email protected]
d:hld45t:generic:intel-galileo-1        Registered 208 days ago by [email protected]
d:hld45t:generic:mbed-k64f-1            Registered 209 days ago by a-hld45t-norczl3hzx
d:hld45t:generic:mbed-lpc1768-1         Registered 209 days ago by a-hld45t-norczl3hzx
d:hld45t:generic:psutil                 Registered 257 days ago by [email protected]
d:hld45t:generic:raspberry-pi-1         Registered 210 days ago by a-hld45t-norczl3hzx
d:hld45t:generic:sigar                  Registered 166 days ago by [email protected]
d:hld45t:generic:ti-bbst-1              Registered 210 days ago by a-hld45t-norczl3hzx
d:hld45t:generic2:intel-galileo-2       Registered 153 days ago by [email protected]
d:hld45t:generic2:mbed-k64f-2           Registered 153 days ago by [email protected]
d:hld45t:generic2:mbed-lpc1768-2        Registered 153 days ago by [email protected]
d:hld45t:generic2:raspberry-pi-2        Registered 153 days ago by [email protected]
d:hld45t:generic2:ti-cc3200-1           Registered 153 days ago by [email protected]
d:hld45t:sdfgh:dfghgfds                 Registered 12 days ago by [email protected]

I suspect this is to due to API pagination design. How to work around this pagination and get full device list?

Or this python client is useless without improving for now.

Disk Buffering feature

Hi,

I would like to know if the ibmiotf library can handle disk buffering ? And if it doesn't, does anyone know what would be my best alternative ?

My use-case is that I have a device that is sending logs throughout the day, if my device loses connection and get it back later on it's fine because the unsent messages are properly stored in RAM. But if the device reboots then I lose everything.

Thanks,

IoT Foundation still appear in some files

The below files still contains reference to IoT Foundation should be replace with IBM Watson Internet of Things Platform

cli.py line 340 - IBM IOT Foundation
\samples\apiExamples\README.rst - Internet of Things Foundation
\samples\managedDevice\DeviceAndFirmwareActions.py - IBM Internet of Things Foundation
\samples\managedDevice\iotpsutilManaged.py - IBM Internet of Things Foundation
\samples\psutil\iotpsutil.py - IBM Internet of Things Foundation
\src\ibmiotf\api.py - IBM Internet of Things Foundation
\src\ibmiotf\device.py - IoT Foundation
\src\ibmiotf\gateway.py - IoT Foundation

Update of device meta data from Watson IOT dashboard produces error on device

Using Watson IOT dashboard to change device metadata produces the following error on the device:

2017-05-07 11:14:50,828 ibmiotf.device.ManagedClient INFO Message received on topic :iotdm-1/device/update with payload {"d":{"fields":[{"field":"metadata","value":{"metadata":"value"}}]}}
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 2630, in _thread_main
self.loop_forever(retry_first_connection=True)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1410, in loop_forever
rc = self.loop(timeout, max_packets)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 926, in loop
rc = self.loop_read(max_packets)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1209, in loop_read
rc = self._packet_read()
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1802, in _packet_read
rc = self._packet_handle()
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2278, in _packet_handle
return self._handle_publish()
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2468, in _handle_publish
self._handle_on_message(message)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2618, in _handle_on_message
t[1](self, self._userdata, message)
File "/usr/local/lib/python2.7/dist-packages/ibmiotf/device.py", line 833, in __onUpdatedDevice
reqId = data['reqId']
KeyError: 'reqId'

Add XML event format support

  • encode should take the data dictionary and convert to an XML string
  • decode should take an XML string and convert to a python dictionary object
  • register the new codec as the default handler for the "xml" format_string in the application, device & gateway clients
  • extend the aplication.httpClient and device.httpClientto support json and xml formats instead of always using json.

Some devices registered successfully returned with APIException 400 RC instead of 202

Obvious bug here:

		elif status == 202:
			raise ibmiotf.APIException(400, "Some devices registered successfully", r.json())
	def registerDevices(self, listOfDevices):
		"""
		Register multiple new devices, each request can contain a maximum of 512KB.
		The response body will contain the generated authentication tokens for all devices.
		You must make sure to record these tokens when processing the response.
		We are not able to retrieve lost authentication tokens
		It accepts accepts a list of devices (List of Dictionary of Devices)
		In case of failure it throws APIException
		"""
		bulkAdd = ApiClient.bulkAddUrl % (self.host )
		r = requests.post(bulkAdd, auth = self.credentials, data = json.dumps(listOfDevices), headers = {'content-type': 'application/json'}, verify=self.verify)

		status = r.status_code

		if status == 201:
			self.logger.debug("Bulk registration successful")
			return r.json()
		elif status == 202:
			raise ibmiotf.APIException(400, "Some devices registered successfully", r.json())
		elif status == 400:
			raise ibmiotf.APIException(400, "Invalid request (No body, invalid JSON, unexpected key, bad value)", r.json())
		elif status == 403:
			raise ibmiotf.APIException(403, "Maximum number of devices exceeded", r.json())
		elif status == 413:
			raise ibmiotf.APIException(413, "Request content exceeds 512KB", r.json())
		elif status == 500:
			raise ibmiotf.APIException(500, "Unexpected error", None)
		else:
			raise ibmiotf.APIException(None, "Unexpected error", None)

ApiClient init needs extra parameter compared to examples

The ApiClient examples all use a single init variable, containing the api options, for example in samples/apiExamples/deviceManagement.py:

apiOptions = {"org": "uguhsp", "id": "myapp", "auth-method": "apikey", "auth-key": "SOME KEY", "auth-token": "SOME TOKEN"}
apiCli = ibmiotf.api.ApiClient(apiOptions)

On the other hand, the ApiClient: init definition is __init__(self, options, logger), requiring an extra parameter (logger), in contradiction with the examples.

Is it wrong lifetime "limit"?

Why?

if lifetime < 3600:
lifetime = 0

If in documentation reverted result:

If your Watson IoT Platform MQTT clients use shared subscriptions, the keep alive interval value can be set only to between 1 and 3600 seconds. If a value of 0 or a value that is greater than 3600 is requested, the Watson IoT Platform broker sets the keep alive interval to 3600 seconds.
https://console.bluemix.net/docs/services/IoT/reference/mqtt/index.html#mqtt-keep-alive

Must be

 if lifetime > 3600: 
     lifetime = 3600 

RuntimeError: dictionary changed size during iteration

I just updated to 0.3.3 and I'm getting this trackback in my application:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/local/lib/python3.5.2/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/local/lib/python3.5.2/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/home/cwhitcher/venvs/python352/lib/python3.5/site-packages/paho/mqtt/client.py", line 2650, in _thread_main
    self.loop_forever(retry_first_connection=True)
  File "/home/cwhitcher/venvs/python352/lib/python3.5/site-packages/paho/mqtt/client.py", line 1481, in loop_forever
    rc = self.loop(timeout, max_packets)
  File "/home/cwhitcher/venvs/python352/lib/python3.5/site-packages/paho/mqtt/client.py", line 1003, in loop
    rc = self.loop_read(max_packets)
  File "/home/cwhitcher/venvs/python352/lib/python3.5/site-packages/paho/mqtt/client.py", line 1284, in loop_read
    rc = self._packet_read()
  File "/home/cwhitcher/venvs/python352/lib/python3.5/site-packages/paho/mqtt/client.py", line 1849, in _packet_read
    rc = self._packet_handle()
  File "/home/cwhitcher/venvs/python352/lib/python3.5/site-packages/paho/mqtt/client.py", line 2311, in _packet_handle
    return self._handle_connack()
  File "/home/cwhitcher/venvs/python352/lib/python3.5/site-packages/paho/mqtt/client.py", line 2372, in _handle_connack
    self.on_connect(self, self._userdata, flags_dict, result)
  File "/home/cwhitcher/venvs/python352/lib/python3.5/site-packages/ibmiotf/application.py", line 272, in on_connect
    for subscription in self._subscriptions:
RuntimeError: dictionary changed size during iteration

I think there needs to be a lock around access to self._subscriptions since it can be modified from multiple threads.

I'll try it out and report back.

Delay in messages sent via publishGatewayEvent

I'm writing a Python3 script that is meant to send messages to WIoT after it completes certain steps in a method. The problem I have is that these messages are never sent in the order I generate them and instead are sent in one big batch once my overall method completes. I believe it has something to do with the way Python handles threads. I have tried a number of ways of solving this but no success.

I understand why it's been written in a non-blocking way but equally need a method to send a message now and only continue once sent (or advice on how I should write my code so it opens up to allow the messages to be sent).

getting problem while subscribing data

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 2580, in _thread_main
self.loop_forever(retry_first_connection=True)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1378, in loop_forever
rc = self.loop(timeout, max_packets)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 897, in loop
rc = self.loop_read(max_packets)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1177, in loop_read
rc = self._packet_read()
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1766, in _packet_read
rc = self._packet_handle()
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2239, in _packet_handle
return self._handle_publish()
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2414, in _handle_publish
self._handle_on_message(message)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2568, in _handle_on_message
t[1](self, self._userdata, message)
File "/usr/local/lib/python2.7/dist-packages/ibmiotf/application.py", line 433, in __onDeviceStatus
if self.deviceStatusCallback: self.deviceStatusCallback(status)
File "simpleApp.py", line 30, in myStatusCallback
print(tableRowTemplate % (status.time.isoformat(), status.device, status.action + " " + status.clientAddr + " (" + status.reason + ")"))
TypeError: coercing to Unicode: need string or buffer, NoneType found

README.txt not found

when run "pip install iot-python.zip", there is an error complain "README.txt not found".
It's in setup.py, line 20 "long_description=open('README.txt').read(),"

TypeError run-time crash after publishing in a loop for a long time

Hello,

After 64k published messages (with qos=0 and no publish call-back defined) the following error occurs and the client ceases to function:

Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/home/mike/.local/lib/python3.5/site-packages/paho/mqtt/client.py", line 2650, in _thread_main
    self.loop_forever(retry_first_connection=True)
  File "/home/mike/.local/lib/python3.5/site-packages/paho/mqtt/client.py", line 1481, in loop_forever
    rc = self.loop(timeout, max_packets)
  File "/home/mike/.local/lib/python3.5/site-packages/paho/mqtt/client.py", line 1019, in loop
    rc = self.loop_write(max_packets)
  File "/home/mike/.local/lib/python3.5/site-packages/paho/mqtt/client.py", line 1309, in loop_write
    rc = self._packet_write()
  File "/home/mike/.local/lib/python3.5/site-packages/paho/mqtt/client.py", line 1895, in _packet_write
    self.on_publish(self, self._userdata, packet['mid'])
  File "/home/mike/.local/lib/python3.5/site-packages/ibmiotf/__init__.py", line 189, in on_publish
    midOnPublish()
TypeError: 'NoneType' object is not callable

This is the function responsible:

    def on_publish(self, mosq, obj, mid):
        with self._messagesLock:
            self.messages = self.messages + 1
            if mid in self._onPublishCallbacks:
                midOnPublish = self._onPublishCallbacks.get(mid)
                del self._onPublishCallbacks[mid]
                midOnPublish()
            else:
                # record the fact that paho callback has already come through so it can be called inline
                # with the publish.
                self._onPublishCallbacks[mid] = None

I believe the problem here is that "mid" is a 16-bit unsigned quantity according to protocol specs, so it will wrap around after 64k "None"s have been uselessly shoved into the _onPublishCallbacks array and eventually the true branch of the condition will be taken and crash when attempting to invoke one of those "None"s..

My work-around is to simply remove the "else" branch of the condition, I see that this is trying to avoid a race condition with the publish thread, but it needs to better handle the case where no call back is defined and not grow this array to 64k entries..

global name 'result' is not defined error while using publisher

I am trying to use application publishCommand function & getting "global name 'result' is not defined error".

Below is the sample code

def start(device_config_file):
    try:
        try:
            # Read from the configuration file
            device_options = ibmiotf.application.ParseConfigFile(device_config_file)
            client = ibmiotf.application.Client(device_options)
        except Exception as e:
            print(str(e))
            sys.exit()
        client.deviceEventCallback = deviceEventCallback
        client.connect()

        mydata = {'switch-led': 'false'}
        while 1:
            client.publishCommand("RasberryPi", "b827ebe3db7a", "command", "json", mydata)
            time.sleep(1)
        client.disconnect()

    except Exception as e:
        print(str(e))
        sys.exit()

Python 3.6 - Error in paho-mqtt port type

I'm using:

  • Python 3.6.3
  • IBMIoT 0.3.1 (latest)
  • paho-mqtt 1.3.1

In a RaspberryPi 3 (4.9.67-v7 latest kernel if I'm not wrong)

The problem is this:

Python 3.6.3 (default, Dec 14 2017, 14:47:50) 
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ibmiotf import gateway
>>> gatewayOptions = gateway.ParseConfigFile("path")
>>> rasp = gateway.Client(gatewayOptions)    
>>> rasp.connect()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/ibmiotf/__init__.py", line 135, in connect
    self.client.connect(self.address, port=self.port, keepalive=self.keepAlive)
  File "/usr/local/lib/python3.6/site-packages/paho/mqtt/client.py", line 767, in connect
    self.connect_async(host, port, keepalive, bind_address)
  File "/usr/local/lib/python3.6/site-packages/paho/mqtt/client.py", line 823, in connect_async
    if port <= 0:
TypeError: '<=' not supported between instances of 'str' and 'int'

In Python2.7 I didn't have any problem using the library.

Looking the code (from ibmiotf/__init__.py), I can't see any place where the port value is different from an integer, but for some reason in client.py it's a string, not an int.

I temporally fix it casting port to int in the self.client.connect call in __init__.py, but somewhere must be a problem either in ibmiotf or paho-mqtt

Add support for play organization

Organization id parsing breaks when the play organization is used, because it is an exception to the rule that all organization IDs are 6 character strings, this prevents the library being used with that organization.

paho-mqtt 1.2.1 version number breaks ibmiotf library

paho-mqtt 1.2.1 was released on 4 Apr 2017. The version string "1.2.1" breaks the ibmiotf python library.

The error is in
/usr/lib/python2.7/site-packages/ibmiotf/__init__.py
line 105 checks for a float but 1.2.1 is no longer a float.
if float(get_distribution('paho-mqtt').version) < 1.1
ValueError: invalid literal for float(): 1.2.1

Here's the trace
$ python ibm-iot-quickstart.py
please check the format of your config file
please check the format of your config file
Configuration file found - connecting to the registered service
Traceback (most recent call last):
File "ibm-iot-quickstart.py", line 145, in <module>
deviceClient = ibmiotf.device.Client(options)
File "/usr/lib/python2.7/site-packages/ibmiotf/device.py", line 105, in __init__
port = self._options['port']
File "/usr/lib/python2.7/site-packages/ibmiotf/__init__.py", line 105, in __init__
if float(get_distribution('paho-mqtt').version) < 1.1 and
(sys.version_info[0] < 3 or (sys.version_info[0] == 3 and
sys.version_info[1] < 2)):
ValueError: invalid literal for float(): 1.2.1

missing check for duplicates when appending to _subscriptions list in application client

Our application creates a client using iot-python/src/ibmiotf/application.py. It then periodicallly, creates a connection and subscribes to a topic using subscribeToDeviceEvents(). (In each of these subscribe requests, the application specifices the same topic.) After receiving messages, the client is disconnected.

We are finding that on each successive call to subscribeToDeviceEvents(), additional subscribe requests are received by the MQTT server. It looks like this is because each time subscribe() is called in subscribeToDeviceEvents(), the topic/qos for the request are added to the _subscriptions list. It seems that before appending a given topic/qos to this list, the application client should check first to see whether the subscription is already in the list.

Seperate HTTP publish into HTTP only client

It's pointless having the http event publish method in a client that already has the MQTT connection.

Create a new device|application.HttpClient seperate from device|application.Client that allows a limited non-MQTT based client to be instantiated for those that wish to not use MQTT.

Error in ibmiotf.device.ParseConfigFile

In version 0.3.2, I get the following error when loading the config file (which was working with version 0.3.1):

Traceback (most recent call last):
  File "xxxx.py", line 6, in <module>
    options = ibmiotf.device.ParseConfigFile("./xxxx.conf")
  File "/home/xxxx/workspaces/python/test_env/lib/python3.5/site-packages/ibmiotf/device.py", line 929, in ParseConfigFile
    port = parms.getint(sectionHeader, "port")
  File "/usr/lib/python3.5/configparser.py", line 816, in getint
    fallback=fallback, **kwargs)
  File "/usr/lib/python3.5/configparser.py", line 806, in _get_conv
    **kwargs)
  File "/usr/lib/python3.5/configparser.py", line 800, in _get
    return conv(self.get(section, option, **kwargs))
  File "/usr/lib/python3.5/configparser.py", line 797, in get
    d)
  File "/usr/lib/python3.5/configparser.py", line 393, in before_get
    self._interpolate_some(parser, option, L, value, section, defaults, 1)
  File "/usr/lib/python3.5/configparser.py", line 410, in _interpolate_some
    p = rest.find("%")
AttributeError: 'int' object has no attribute 'find'

HttpClient does not work

('Caught exception', AttributeError("HttpClient instance has no attribute '_messageEncoderModules'",))

when attempting to use the HttpClient

addDeviceType does not allow creation of gateway types

The addDeviceType method does not allow for the creation of gateway types. It accepts, apparently, a parameter to specify the device class. But it sets a default value of 'Device', and then doesn't pass this parameter to the REST call anyway - at least as far as I can see.

This requires python developers to check what kind of type they want to create, and then code a separate REST call to create a gateway type.

Fail in Application Mode

Hi!

I'm trying to use version 0.2.2 of the library, but does not work. I think there is a bug in line 229 in application.py, because you iterate the subscriptions like 'subscription', so you should use 'subscription' object, not 'subscriptions' to access to the elements.

I made the change locally, but other error appear: Now, I can connect, but the device is connected and disconnected constantly. Can you check it?. Meanwhile I will continue using the version 0.1.8. :)

https://github.com/ibm-messaging/iot-python/blob/master/src/ibmiotf/application.py#L229

Regards.
Paco Martín.

Reconnect capabilities

WIOT client works great most of times.
On some occasions (which i can't explain), there are disconnections from WIOT platform.
Internet connections might return after these occasions , but WIOT won't try to reconnect or notify on anyway on disconnections.

Please try to add this capabilities to the python package

Unreachable code

There are a number of if statements where code similar to the following is executed:

if not self.connectEvent.wait():
    self.logger.warning("Unable ... not currently connected")
    return False

Those log messages can never be executed and False can never be returned. The threading.Event wait() method always returns True unless a timeout value is given and the wait times out. Since there is no timeout, the call will always block.

Should the wait calls be modified to something like so that the connectEvent flag is checked:

# The number of seconds to block for the connectEvent event to be set.
CONNECT_WAIT_SEC = 0.001

if not self.connectEvent.wait(CONNECT_WAIT_SEC):
    self.logger.warning("Unable ... not currently connected")
    return False

constructing multiple clients creates multiple loghandlers

if in a single process you construct more than 1 client, eg:

`loop{

appCli = ibmiotf.application.Client(opts)

appCli.connect()

...

appCli.disconnect() `

}

on the second loop you get 2 entries per log, on the third you get 3......

ApiClient() is not used correctly in sample files

In sample you can find lines like

apiCli = ibmiotf.api.ApiClient(apiOptions)

should be

apiCli = ibmiotf.api.ApiClient(apiOptions, logger)

Note: logger needs to be defined first and import the logging libraries

Code hangs up when using on_publish callback

I have a program which checks memory consumption of a python mqtt client while sending messages with different sizes, different qos and different amount of sending times here.
I am using a callback to check if all messages have successfully been published.

My code sometimes(!) hangs up when trying to send a JSON payload of size 527 bytes with qos=1.
In sometimes I mean this either happens when I try to send this combination 10 times or the when I later try to send it again 100 times.
This code works fine when I call "publishEvent" without the callback.
While debugging I found out that this line in the paho lib hangs.
This happens on Windows and Linux alike.

When I attach my callback function to the paho client directly like this
the code again runs fine.

Need to call Client loop_stop when CONNECT timeout

In the connect method of init.py, when the TIMEOUT is reached, it just raised the EXCEPTION. however, It didn't call loop_stop to stop or clean up the thread (Note: loop_start is called few lines above).

Add support for custom MQTT port usage

The platform allows clients to connect to alternate ports, primarily aimed at envronments where restrictive firewalls are in force.

Alternate MQTT (1883) = 80
Alternate MQTTS (8883) = 443

AbstractClient should support alt ports

Not receiving gateway commands after "Unexpected disconnect"

Step to reproduce

  • Run the gatewaySubscribeCommand.py with valid gateway options and wait for the Connected successfully message
    Note: Here you can send a Gateway Command. You should receive it. Everything works.
  • Block the Internet connection (e.g firewall) and wait for the Unexpected disconnect message (>1m)
  • Unblock the Internet connection and wait for the Connected successfully message

When we are in that state, we don't receive the Gateway Commands anymore.

Application subscription issues

In reviewing one of the Watson IoT Platform python scripts which uses this iot-python library, I would suggest to fix (or enhance) the current code for the followings:

crash in publishEvent with data containing non-json serializable fields

I've been writing a custom encoder to be able to send messages to watson iot in a custom binary format.

Line 166 in device.py does json.dumps(data) before running the data through the encoder. This means that the data you send to watson must be json serializable even if you have your own encoder that does not use json at all.

This behaviour seems undesirable, there are a two fixes i can think of:

  1. replace json.dumps(data) with str(data). Smallest possible fix but most objects only print "<file.class at 0x00...>"
  2. move the log statement down to line 171 and log str(payload). Works for json encoders but has the same problem as point 1 for other payload types.

If there is a consensus on the desired behaviour I will create a pull request with the fix

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.