forked from mzuliani-ibm/iot-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Quickstart device code
- Loading branch information
David Parker
committed
Apr 16, 2014
1 parent
fded3a8
commit b370191
Showing
4 changed files
with
252 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
IBM Contributor License Agreement | ||
================================= | ||
|
||
Version 1.0.0 January 14, 2014 | ||
|
||
In order for You (as defined below) to make intellectual property Contributions (as defined below) now or in the future to IBM GitHub repositories, | ||
You must agree to this Contributor License Agreement ("CLA"). | ||
|
||
Please read this CLA carefully before accepting its terms. By accepting the CLA, You are agreeing to be bound by its terms. | ||
If You submit a Pull Request against an IBM repository on GitHub You must include in the Pull Request a statement of Your acceptance of this CLA. | ||
|
||
As used in this CLA: | ||
(i) "You" (or "Your") shall mean the entity that is making this Agreement with IBM; | ||
(ii)"Contribution" shall mean any original work of authorship, including any modifications or additions to an existing work, that is submitted by You to IBM for inclusion in, | ||
or documentation of, any of the IBM GitHub repositories; | ||
(iii) "Submit" (or "Submitted") means any form of communication sent to IBM (e.g. the content You post in a GitHub Issue or submit as part of a GitHub Pull Request). | ||
|
||
This agreement applies to all Contributions You Submit. | ||
|
||
This CLA, and the license(s) associated with the particular IBM GitHub repositories You are contributing to, provides a license to Your Contributions to IBM and downstream consumers, | ||
but You still own Your Contributions, and except for the licenses provided for in this CLA, You reserve all right, title and interest in Your Contributions. | ||
|
||
IBM requires that each Contribution You Submit now or in the future comply with the following four commitments. | ||
|
||
1) You will only Submit Contributions where You have authored 100% of the content. | ||
2) You will only Submit Contributions to which You have the necessary rights. This means that if You are employed You have received the necessary permissions from Your employer to make the | ||
Contributions. | ||
3) Whatever content You Contribute will be provided under the license(s) associated with the particular IBM GitHub repository You are contributing to. | ||
4) You understand and agree that IBM GitHub repositories and Your contributions are public, and that a record of the contribution (including all personal information You submit with it) | ||
is maintained indefinitely and may be redistributed consistent with the license(s) involved. | ||
You will promptly notify the Eclipse Foundation if You become aware of any facts or circumstances that would make these commitments inaccurate in any way. | ||
To do so, please create an Issue in the appropriate GitHub repository. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,21 @@ | ||
iot-py-psutil | ||
============= | ||
#IBM Internet of Things Python PSUtil Adapter | ||
|
||
Contains QuickStart, SDKs and samples for connecting a device running Python to the IBM Internet of Things cloud and sending system utilization data. | ||
|
||
Enables publishing of basic system utilization statistics to the IBM Internet of Things Cloud service from any device that supports a Python 2.7 runtime. | ||
|
||
The following data points are supported: | ||
* CPU utilization (%) | ||
* Memory utilization (%) | ||
* Outbound network utilization across all network interfaces (kb/s) | ||
* Inbound network utilization across all network interfaces (kb/s) | ||
|
||
|
||
Platform | ||
------------ | ||
* [Python 2.7](https://www.python.org/download/releases/2.7) | ||
|
||
Dependencies | ||
------------ | ||
* [paho-mqtt](http://git.eclipse.org/c/paho/org.eclipse.paho.mqtt.python.git/) | ||
* [psutil](https://code.google.com/p/psutil/) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
#IBM Internet of Things Python PSUtil QuickStart Adapter | ||
|
||
Getting Started | ||
--------------- | ||
1 [Install Python](https://www.python.org/download/releases/2.7) | ||
|
||
2 [Install pip](http://pip.readthedocs.org/en/latest/installing.html). Windows users may prefer to use [pip-Win](https://sites.google.com/site/pydatalog/python/pip-for-windows) | ||
|
||
3 Install the [paho-mqtt](http://git.eclipse.org/c/paho/org.eclipse.paho.mqtt.python.git/) and [psutil](https://code.google.com/p/psutil/) Python modules | ||
|
||
```bash | ||
pip install paho-mqtt | ||
pip install psutil | ||
``` | ||
|
||
4 Launch the program | ||
```bash | ||
$ python iotqs-pypsinfo.py | ||
Connected successfully - Your device ID is ca51af86af39 | ||
* http://quickstart.internetofthings.ibmcloud.com/?deviceId=ca51af86af39 | ||
Visit the QuickStart portal to see this device's data visualized in real time and learn more about the IBM Internet of Things Cloud | ||
(Press Ctrl+C to disconnect) | ||
``` | ||
5 Visualize | ||
Visit the [IBM Internet of Things QuickStart Portal](http://quickstart.internetofthings.ibmcloud.com) and enter your device ID to see real time visualizations of | ||
the data sent from your device. | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,172 @@ | ||
import getopt | ||
import time | ||
import threading | ||
import sys | ||
import psutil | ||
import platform | ||
import json | ||
import signal | ||
import paho.mqtt.client as paho | ||
from uuid import getnode as get_mac | ||
|
||
|
||
class ClientThread(threading.Thread): | ||
|
||
def __init__(self, deviceId, deviceName, stopEvent, verbose=False): | ||
super(ClientThread, self).__init__() | ||
self.brokerAddress = "messaging.quickstart.internetofthings.ibmcloud.com" | ||
self.brokerPort = 1883 | ||
self.keepAlive = 60 | ||
self.deviceId = deviceId | ||
self.deviceName = deviceName | ||
self.verbose = verbose | ||
self.stopEvent = stopEvent | ||
|
||
self.messages = 0 | ||
self.topic = 'iot-1/d/'+self.deviceId+'/evt/py-psutil-quickstart/json' | ||
|
||
self.client = paho.Client("quickstart:"+deviceId, clean_session=True) | ||
|
||
#attach MQTT callbacks | ||
if self.verbose: | ||
self.client.on_log = self.on_log | ||
self.client.on_connect = self.on_connect | ||
self.client.on_publish = self.on_publish | ||
self.client.on_disconnect = self.on_disconnect | ||
|
||
|
||
def run(self): | ||
self.client.connect(self.brokerAddress, port=self.brokerPort, keepalive=self.keepAlive) | ||
self.client.loop_start() | ||
|
||
if self.verbose: | ||
print "Publishing to " + self.topic | ||
|
||
start = time.time() * 1000 | ||
|
||
# Take initial reading | ||
psutil.cpu_percent(percpu=False) | ||
|
||
while(not self.stopEvent.is_set()): | ||
ioBefore = psutil.net_io_counters() | ||
time.sleep(1) | ||
ioAfter = psutil.net_io_counters(); | ||
|
||
data = { | ||
'name' : self.deviceName, | ||
'cpu' : psutil.cpu_percent(percpu=False), | ||
'mem' : psutil.virtual_memory().percent, | ||
'network': { | ||
'up' : "%.2f" % ((ioAfter.bytes_sent - ioBefore.bytes_sent)/float(1024)), | ||
'down' : "%.2f" % ((ioAfter.bytes_recv - ioBefore.bytes_recv)/float(1024)) | ||
} | ||
} | ||
if self.verbose: | ||
print "Datapoint = " + json.dumps(data) | ||
|
||
payload = { 'd' : data } | ||
self.client.publish(self.topic, payload=json.dumps(payload), qos=0, retain=False) | ||
|
||
self.client.disconnect() | ||
self.client.loop_stop() | ||
|
||
elapsed = ((time.time() * 1000) - start) | ||
msgPerSecond = self.messages/(elapsed/1000) | ||
print "Messages published:"+ str(self.messages) + ", life:" + "%.0f" % (elapsed/1000) + "s, msg/s:" + "%.2f" % msgPerSecond | ||
|
||
|
||
def on_log(self, mqttc, obj, level, string): | ||
print string | ||
|
||
''' | ||
This is called after the client has received a CONNACK message from the broker in response to calling connect(). | ||
The parameter rc is an integer giving the return code: | ||
0: Success | ||
1: Refused - unacceptable protocol version | ||
2: Refused - identifier rejected | ||
3: Refused - server unavailable | ||
4: Refused - bad user name or password (MQTT v3.1 broker only) | ||
5: Refused - not authorised (MQTT v3.1 broker only) | ||
''' | ||
def on_connect(self, mosq, obj, rc): | ||
if rc == 0: | ||
print "Connected successfully - Your device ID is %s" % self.deviceId | ||
print " * http://quickstart.internetofthings.ibmcloud.com/?deviceId=%s" % (self.deviceId) | ||
print "Visit the QuickStart portal to see this device's data visualized in real time and learn more about the IBM Internet of Things Cloud" | ||
print "" | ||
print "(Press Ctrl+C to disconnect)" | ||
else: | ||
print "Connection failed: RC=" + str(rc) | ||
|
||
''' | ||
This is called when the client disconnects from the broker. The rc parameter indicates the status of the disconnection. | ||
When 0 the disconnection was the result of disconnect() being called, when 1 the disconnection was unexpected. | ||
''' | ||
def on_disconnect(self, mosq, obj, rc): | ||
if rc == 1: | ||
print "Unexpected disconnect" | ||
|
||
''' | ||
This is called when a message from the client has been successfully sent to the broker. | ||
The mid parameter gives the message id of the successfully published message. | ||
''' | ||
def on_publish(self, mosq, obj, mid): | ||
if self.verbose: | ||
print "Message " + str(mid) + " published" | ||
self.messages = self.messages + 1 | ||
|
||
|
||
|
||
def interruptHandler(signal, frame): | ||
print "Closing connection to the IBM Internet of Things Cloud service" | ||
deviceStopEvent.set() | ||
sys.exit(0) | ||
|
||
def usage(): | ||
print( | ||
"IOTQS-PYPSINFO: Publish basic system utilization statistics to the IBM Internet of Things Cloud service." + "\n" + | ||
"\n" + | ||
"Datapoints sent:" + "\n" + | ||
" name The name of this device. Defaults to hostname ('%s')" % platform.node() + "\n" + | ||
" cpu Current CPU utilization (%)" + "\n" + | ||
" mem Current memory utilization (%)" + "\n" + | ||
" network.up Current outbound network utilization across all network interfaces (kb/s)" + "\n" + | ||
" network.down Current inbound network utilization across all network interfaces (kb/s)" + "\n" + | ||
"\n" + | ||
"Options: " + "\n" + | ||
" -h, --help Display help information" + "\n" + | ||
" -n, --name Override the default value of the 'name' datapoint" + "\n" + | ||
" -v, --verbose Be more verbose" | ||
) | ||
|
||
if __name__ == "__main__": | ||
try: | ||
opts, args = getopt.getopt(sys.argv[1:], "hn:v", ["help", "name=", "verbose"]) | ||
except getopt.GetoptError as err: | ||
print str(err) | ||
usage() | ||
sys.exit(2) | ||
|
||
verbose = False | ||
deviceId = str(hex(int(get_mac())))[2:-1] | ||
deviceName = platform.node() | ||
|
||
for o, a in opts: | ||
if o in ("-v", "--verbose"): | ||
verbose = True | ||
elif o in ("-n", "--name"): | ||
deviceName = a | ||
elif o in ("-h", "--help"): | ||
usage() | ||
sys.exit() | ||
else: | ||
assert False, "unhandled option" + o | ||
|
||
signal.signal(signal.SIGINT, interruptHandler) | ||
deviceStopEvent = threading.Event() | ||
|
||
device = ClientThread(deviceId, deviceName, deviceStopEvent, verbose=verbose) | ||
device.start() | ||
|
||
while True: | ||
time.sleep(1) |