Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Objetivos
Crear un circuito de prototipo
Usar la API de RESTful de Cisco Spark
Crear un “robot” de mensajería simple para interactuar con el mundo físico
Aspectos básicos/situación
En esta práctica de laboratorio aprenderá a crear un "robot" de mensajería simple. El robot de mensajería
detectará los comandos de Cisco Spark y controlará el mundo físico representado por los pines de GPIO de
Raspberry Pi.
Recursos necesarios
PC con acceso a Internet
Conexión a Internet por Wi-Fi o Ethernet con DHCP y sin filtro de tráfico
Raspberry Pi configurado para el acceso a PL-App
Placa de prueba, resistores, LED, cables
https://static-course-assets.s3.amazonaws.com/IoTFCT201/es/course/files/3.2.5.14 Lab - Interacting with a physical world from Cisco Spark.html 1/11
3/4/2019 3.2.5.14 Práctica de laboratorio: interacción con el mundo físico de Cisco Spark
1. Conecte un extremo del cable de acoplamiento negro al conector a9 de la placa de prueba y el otro
extremo al pin 9 GPIO físico en Raspberry Pi.
2. Conecte un extremo del cable de acoplamiento rojo al conector a14 de la placa de prueba y el otro
extremo al pin 11 GPIO físico (BCM17) en Raspberry Pi.
https://static-course-assets.s3.amazonaws.com/IoTFCT201/es/course/files/3.2.5.14 Lab - Interacting with a physical world from Cisco Spark.html 2/11
3/4/2019 3.2.5.14 Práctica de laboratorio: interacción con el mundo físico de Cisco Spark
https://static-course-assets.s3.amazonaws.com/IoTFCT201/es/course/files/3.2.5.14 Lab - Interacting with a physical world from Cisco Spark.html 3/11
3/4/2019 3.2.5.14 Práctica de laboratorio: interacción con el mundo físico de Cisco Spark
En [ ]:
# Import the GPIO modules to control the GPIO pins of the Raspberry Pi
import RPi.GPIO as GPIO
# Set the desired pin numbering scheme:
GPIO.setmode(GPIO.BCM)
1. Ejecute la celda siguiente para verificar que el LED esté parpadeando y que funcione el acceso de
GPIO.
En [ ]:
import time
for i in range(5):
print("ON")
GPIO.output(LEDPin, True)
time.sleep(1)
print("OFF")
GPIO.output(LEDPin, False)
time.sleep(1)
https://static-course-assets.s3.amazonaws.com/IoTFCT201/es/course/files/3.2.5.14 Lab - Interacting with a physical world from Cisco Spark.html 4/11
3/4/2019 3.2.5.14 Práctica de laboratorio: interacción con el mundo físico de Cisco Spark
4. Obtenga más información sobre las API de SPARK en la Guía de referencia rápida de API de Spark
(https://developer.ciscospark.com/quick-reference.html)
5. Ingrese su clave de token en la celda de abajo y ejecútela para definir la variable
sparkAuthorizationKey que se usará para autenticar las solicitudes en los próximos pasos.
En [ ]:
# Define a local variable in Python that will hold our Authentication API KEY:
sparkAuthorizationKey = 'Bearer YjcxZDkxMTItMWFhMy00NjQ1LTxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx';
Nota: El Token de acceso de Cisco Spark vence en 2 años y se inactiva inmediatamente cuando cierra sesión
en developer.ciscospark.com. Si el código devuelve un código de error 401
(https://developer.ciscospark.com/errors.html), puede que necesite crear un nuevo token y modificar el
código para que funcione correctamente.
La mayoría de los mensajes que intercambian el cliente de API y el servidor de API tienen un formato
especial. Los más comunes son XML y JSON. La API de Cisco Spark usa JSON para codificar mensajes.
Para trabajar con los datos cifrados de JSON, importe en Python el módulo json.
En [ ]:
import requests
import json
import time
https://static-course-assets.s3.amazonaws.com/IoTFCT201/es/course/files/3.2.5.14 Lab - Interacting with a physical world from Cisco Spark.html 5/11
3/4/2019 3.2.5.14 Práctica de laboratorio: interacción con el mundo físico de Cisco Spark
En [ ]:
# Using the requests library, create a new HTTP GET Request against the Spark AP
I Endpoint for Spark Rooms:
# the local object "r" will hold the returned data:
r = requests.get( "https://api.ciscospark.com/v1/rooms",
headers={'Authorization':sparkAuthorizationKey}
)
# Check if the response from the API call was OK (resp. code 200)
if(r.status_code != 200):
print("Something wrong has happened:")
print("ERROR CODE: {} \nRESPONSE: {}".format(r.status_code, r.text))
assert()
1. Use el siguiente código para ver el contenido de los datos devueltos. Los datos devueltos de la API
de Spark usualmente están formateados con el cifrado JSON. La función json.dumps() genera
una salida de más fácil lectura.
En [ ]:
jsonData = r.json()
print(
json.dumps(
jsonData,
indent=4
)
)
1. Para revisar de manera programática la lista de salas, puede usar el código siguiente:
En [ ]:
rooms = r.json()['items']
for room in rooms:
print ("Room name: '" + room['title'] + "' ID: " + room['id'])
1. Para identificar de manera programática una sala con un nombre específico, puede usar el código
siguiente.
https://static-course-assets.s3.amazonaws.com/IoTFCT201/es/course/files/3.2.5.14 Lab - Interacting with a physical world from Cisco Spark.html 6/11
3/4/2019 3.2.5.14 Práctica de laboratorio: interacción con el mundo físico de Cisco Spark
En [ ]:
# Replace contents of this varialble with a real room name from your Cisco Spark
account
roomNameToSearch = 'Jozef'
rooms = r.json()['items']
for room in rooms:
#print "Room name: '" + room['title'] + "' ID: " + room['id']
if(room['title'].find(roomNameToSearch) != -1):
print ("Found rooms with the word " + roomNameToSearch)
print ("Room name: '" + room['title'] + "' ID: " + room['id'])
roomIdToMessage = room['id']
roomTitleToMessage = room['title']
break
if(roomIdToMessage == None):
print("Did not found any room with " + roomNameToSearch + " name in it.")
else:
print("A valid room has been found and this is the room id: " + roomIdToMess
age)
En [ ]:
print(roomIdToMessage)
https://static-course-assets.s3.amazonaws.com/IoTFCT201/es/course/files/3.2.5.14 Lab - Interacting with a physical world from Cisco Spark.html 7/11
3/4/2019 3.2.5.14 Práctica de laboratorio: interacción con el mundo físico de Cisco Spark
En [ ]:
# define the mandatory or optional GET parameters for the `messages` API endpoin
t:
getMessagesUrlParameters = {
# mandatory parameter - the room ID
"roomId": roomIdToMessage,
# optional parameter - number of the last messages to return
"max": 8
}
# Using the requests library, create a new HTTP GET Request against the Spark AP
I Endpoint for Spark Messages:
# the local object "r" will hold the returned data:
r = requests.get( "https://api.ciscospark.com/v1/messages",
params=getMessagesUrlParameters,
headers={'Authorization':sparkAuthorizationKey}
)
if(r.status_code != 200):
print("Something wrong has happened:")
print("ERROR CODE: {} \nRESPONSE: {}".format(r.status_code, r.text))
assert()
1. Use el siguiente código para ver el contenido de los datos devueltos. Los datos devueltos de la API
de Spark usualmente están formateados con el cifrado JSON.
En [ ]:
jsonData = r.json()
print(
json.dumps(
jsonData,
indent=4
)
)
1. El código siguiente creará un bucle para buscar en los mensajes hasta identificar un mensaje con
un comando (por ejemplo, mensaje /Turn On o /Turn Off). Una vez detectado dicho mensaje,
el bucle se rompe y se muestra un mensaje informativo.
2. Intente ejecutar la celda de código siguiente. Si usted u otra persona de la sala de Spark anterior
ingresaron el mensaje /Turn On o /Turn Off, lo verán aquí.
NOTA: si no ingresó el mensaje /Turn On o /Turn Off en la sala de Spark antes de este paso,
vuelva a ejecutar la celda de código del Paso 4 para obtener todos los mensajes nuevos de la sala
de Spark.
https://static-course-assets.s3.amazonaws.com/IoTFCT201/es/course/files/3.2.5.14 Lab - Interacting with a physical world from Cisco Spark.html 8/11
3/4/2019 3.2.5.14 Práctica de laboratorio: interacción con el mundo físico de Cisco Spark
En [ ]:
messages = jsonData['items']
for message in messages:
print("Message: " + message['text'])
if(message['text'] == '/Turn On'):
messageId = message['id']
print("Found a command message to TURN ON the LED!")
break
if(message['text'] == '/Turn Off'):
messageId = message['id']
print("Found a command message to TURN OFF the LED!")
break
https://static-course-assets.s3.amazonaws.com/IoTFCT201/es/course/files/3.2.5.14 Lab - Interacting with a physical world from Cisco Spark.html 9/11
3/4/2019 3.2.5.14 Práctica de laboratorio: interacción con el mundo físico de Cisco Spark
En [ ]:
lastMessageId = None
while True:
# the code should not hammer the API service with too many reqeuests in a sh
ort time
# to limit the number of requests in the while loop, begin with a short 1 s
econd delay:
time.sleep(1)
print("Next iteration is starting ...")
# define the mandatory or optional GET parametrs for the `messages` API endp
oint:
getMessagesUrlParameters = {
# mandatory parameter - the room ID
"roomId": roomIdToMessage,
# optional parameter - number of the last messages to return
# only interested in the very last message in the room
# thefore max = 1
"max": 1
}
# Using the requests library, creare a new HTTP GET Request against the Spar
k API Endpoint for Spark Messages:
# the local object "r" will hold the returned data:
r = requests.get( "https://api.ciscospark.com/v1/messages",
params=getMessagesUrlParameters,
headers={'Authorization':sparkAuthorizationKey}
)
if(r.status_code != 200):
print("Something wrong has happened:")
print("ERROR CODE: {} \nRESPONSE: {}".format(r.status_code, r.text))
assert()
Reflexión:
Intente actualizar el código y el circuito electrónico para poder controlar el mundo físico y los sensores de
Cisco Spark. En ese caso, podría hacer preguntas como esta en Cisco Spark: “¿Cuál es la temperatura?”.
© 2017 Cisco y/o sus filiales. Todos los derechos reservados. Este documento es información pública
de Cisco.
https://static-course-assets.s3.amazonaws.com/IoTFCT201/es/course/files/3.2.5.14 Lab - Interacting with a physical world from Cisco Spark.html 11/11