Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python e o Munto IoT

Python e o Munto IoT

A utilização de Python em dispositivos IoT com os protocolos mais utilizados (MQTT e CoAP).

Avatar for Tiago Martins

Tiago Martins

October 04, 2016
Tweet

More Decks by Tiago Martins

Other Decks in Programming

Transcript

  1. AIOCOAP - CLIENT import asyncio from aiocoap import Context, Message,

    GET @asyncio.coroutine def main(): protocol = yield from Context.create_client_context() request = Message(code=GET) request.set_request_uri('coap://192.168.1.110/time') try: response = yield from protocol.request(request).response except Exception as e: print('Failed to fetch resource: {}'.format(e)) print('Result: {!s}\n{!r}'.format(response.code, response.payload)) if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) 3 . 6
  2. AIOCOAP - SERVER import asyncio import aiocoap.resource as resource import

    aiocoap def main(): # Resource tree creation root = resource.Site() root.add_resource(('time',), TimeResource()) asyncio.async(aiocoap.Context.create_server_context(root)) asyncio.get_event_loop().run_forever() if __name__ == "__main__": main() 3 . 7
  3. AIOCOAP - TIME class TimeResource(resource.ObservableResource): def __init__(self): super(TimeResource, self).__init__() self.notify()

    def notify(self): self.updated_state() asyncio.get_event_loop().call_later(6, self.notify) @asyncio.coroutine def render_get(self, request): current = datetime.datetime.now() payload = current.strftime("%Y-%m-%d %H:%M").encode('ascii') return aiocoap.Message(code=aiocoap.CONTENT, payload=payload) 3 . 8
  4. PUBLISHER import paho.mqtt.publish as publish msgs = [{'topic': "kids/yolo", 'payload':

    "jump"}, {'topic': "adult/pics", 'payload': "some photo"}, {'topic': "adult/news", 'payload': "extra extra"}, {'topic': "adult/news", 'payload': "super extra"}] host = "localhost" if __name__ == '__main__': # publish a single message publish.single(topic="kids/yolo", payload="just do it", hostname=host) # publish multiple messages publish.multiple(msgs, hostname=host) 4 . 5
  5. SUBSCRIBER import paho.mqtt.client as paho if __name__ == '__main__': client

    = paho.Client() client.on_message = on_message client.on_publish = on_publish # client.tls_set('root.ca', certfile='c1.crt', keyfile='c1.key') client.connect("192.168.1.111", 1883, 60) client.subscribe("kids/yolo", 0) client.subscribe("adult/#", 0) while client.loop() == 0: pass 4 . 6
  6. SUBSCRIBER - CONT. def on_message(mosq, obj, msg): print("{} {} {!s}".format(msg.topic,

    msg.qos, msg.payload)) mosq.publish('pong', 'ack', 0) def on_publish(mosq, obj, mid): pass 4 . 7
  7. RPI.GPIO import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.OUT) GPIO.output(12, GPIO.HIGH)

    chan_list = (11, 12) GPIO.output(chan_list, (GPIO.HIGH, GPIO.LOW)) # first LOW, second HIGH GPIO.cleanup() 5 . 3
  8. RPI.GPIO - LED DIMMER from itertools import chain import time

    import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.OUT) p = GPIO.PWM(12, 50) # channel=12 frequency=50Hz p.start(0) while True: for dc in chain(range(0, 101, 5), range(100, -1, -5)): p.ChangeDutyCycle(dc) time.sleep(0.1) p.stop() GPIO.cleanup() 5 . 4
  9. ADAFRUIT - MCP3008 import time import spidev as SPI import

    Adafruit_MCP3008 SPI_PORT = 0 SPI_DEVICE = 0 mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) while True: value = 0 # The read_adc function will get the value of the specified channel value = mcp.read_adc(0) temp = value * 100 * 3.3 / 1023 # Print the ADC values. print('Temp: {:.2f}°C'.format(temp)) time.sleep(0.5) 5 . 5
  10. CÓDIGO import time import json import spidev as SPI import

    Adafruit_MCP3008 import paho.mqtt.publish as publish SPI_PORT = 0 SPI_DEVICE = 0 mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) host = 'localhost' while True: value = 0 # The read_adc function will get the value of the specified channel value = mcp.read_adc(0) temp = value * 100 * 3.3 / 1023 temp_json = json.dumps({'temperature': '{0:.2f}'.format(temp)}) # Print the ADC values. publish.single(topic='demo/temp', payload=temp_json, hostname=host) time.sleep(0.5) 6 . 3