diff --git a/.gitignore b/.gitignore index dfed49f9f5e..c5a13784804 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ js/reveal.min.js *.swp *.swo all.tar.gz +.vscode/ \ No newline at end of file diff --git a/CONTRIBUTING-es.md b/CONTRIBUTING-es.md new file mode 100644 index 00000000000..006e1d1d1e9 --- /dev/null +++ b/CONTRIBUTING-es.md @@ -0,0 +1,23 @@ +# Guía para colaboradores + +Por favor, mantenga el [gestor de incidencias](http://github.com/cubantech/slides.cuban.tech/issues) limitado a **informes de errores**, **solicitudes de funciones** y **solicitudes de cambios**. + +## Soporte personalizado + +Si usted requiere de soporte personalizado o o tiene preguntas de configuración, el mejor lugar para hacerlas es [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). + +## Informes de errores + +Al reportar una incidencia, asegúrese de incluir información sobre el navegador y el sistema operativo en el que se encuentra, así como los pasos necesarios para reproducir el problema. Si es posible, incluya un enlace a una presentación de ejemplo donde se pueda probar el error. + +## Solicitudes de Cambios + +- Debe seguir el estilo de codificación del archivo en el que trabaja, lo más importante: + - tabs para identar + - Cadenas de una sola cita +- Debe hacerse hacia la **rama master**. +- Debe ser enviado desde una rama de la característica/tema (no desde su master) + +## Plugins + +Por favor, no envíe plugins como solicitudes pull. Deberían mantenerse en su propio repositorio separado. Más información aquí: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c2091e88fe1..0dd870adbfe 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,23 +1,23 @@ ## Contributing -Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. - +Please keep the [issue tracker](http://github.com/cubantech/slides.cuban.tech/issues) limited to **bug reports**, **feature requests** and **pull requests**. ### Personal Support -If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). +If you require personalized support or have configuration questions, the best place to ask questions is [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). ### Bug Reports -When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. +When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. ### Pull Requests + - Should follow the coding style of the file you work in, most importantly: - Tabs to indent - Single-quoted strings -- Should be made towards the **dev branch** +- Should be made towards the **master branch** - Should be submitted from a feature/topic branch (not your master) - ### Plugins + Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/README-es.md b/README-es.md new file mode 100644 index 00000000000..95c5c82996f --- /dev/null +++ b/README-es.md @@ -0,0 +1,3 @@ +# slides.cuban.tech + +Version en español de las Diapositivas de los CubanTech meetups diff --git a/README.md b/README.md new file mode 100644 index 00000000000..fd2736d5321 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# slides.cuban.tech + +English version of the slides of the CubanTech meetups diff --git a/dapps-es.md b/dapps-es.md new file mode 100644 index 00000000000..39bb886e433 --- /dev/null +++ b/dapps-es.md @@ -0,0 +1,1058 @@ +# Blockchain, DApps y Blockstack + +## Conceptos básicos para empezar + +---------------- + +### Estas diapositivas: [slides.cuban.tech/dapps.html](http://slides.cuban.tech/dapps.html) + +---------------- + +### Información Wifi + +Red: cubantech + +Contraseña: meet-ups + +---------------- + +## Esbozo + +- Máquinas de estado replicadas (denominadas RSM) +- Herramientas de infraestructura, gestión y administración +- Relación entre RSM y Blockchain +- Reglas de ejecución y consenso +- Teoría General de DApps +- Vista general de Blockstack +- RSM de DApp independiente de blockchain con VirtualChain + +Notas sobre la red Bitcoin P2P entre + +---------------- + +## Máquinas de Estado - Estados + +![Estados](img/rsm.states.png) + +---------------- + +## Máquinas de estado - Entradas + +![Entradas](img/rsm.inputs.png) + +---------------- + +## Máquinas de Estado - Transición + +![transición](img/rsm.transition.png) + +---------------- + +## El problema de la escalabilidad + +![Problema de Escalabilidad](img/rsm.scale.png) + +-- + +## Estadísticas de Bitcoin + +![Estadísticas de Bitcoin](img/bitcoin.stats.png) + +---------------- + +## Servicios distribuidos como máquinas de estado + +- Tolerancia a fallos más allá de los procesadores de un solo nodo +- Réplicas de un único servidor ejecutado en procesadores separados +- Protocolos para interacciones de clientes con réplicas +- Aislamiento físico y eléctrico para fallos independientes del servidor +- Asumamos que la máquina de estado determinista + - .... incluso si Turing completo es posible + +---------------- + +## El enfoque de la máquina de estado + +- Implantar réplicas del software +- Recibir las solicitudes de los clientes (las entradas) +- Pedir las entradas +- Ejecute la transición de SM una y otra vez +- Supervisar las réplicas en busca de diferencias de estado o de salida. + +---------------- + +## El enfoque de la máquina de Estado + +### Desplegar software en múltiples nodos + +[![Logo docker Cuba](img/dockercuba.logo.png)](http://docker.cuban.tech) + +[docker.cuban.tech](http://docker.cuban.tech) + +- Repositorios de paquetes de software + - por ejemplo[bitcoind @ Debian](https://packages.debian.org/bitcoind),[Blockstack apt repo](https://packages.blockstack.com), .... +- Contenedores y registros + - Por ejemplo,[Lisk](https://hub.docker.com/u/lisk/),[Blockstack](https://hub.docker.com/u/blockstack), .... Docker Hub +- Herramientas CM (Ansible, Puppet, Chef, Habitat, ....) + +---------------- + +## Estado de CM - Q1 2017 + +![Forrester Wave](img/forrester_wave_cm_q1.jpg) + +---------------- + +## El enfoque de máquina de estado + +- Implantar réplicas del software +- Recibir las peticiones del cliente (es decir, las entradas) +- Pedir las entradas +- Ejecute la transición de SM una y otra vez +- Supervisar las réplicas en busca de diferencias de estado o de salida. + +---------------- + +## El enfoque de la máquina estatal + +### Recibir las peticiones de los clientes + +- Múltiples soluciones +- p. ej., transacciones Bitcoin + +---------------- + +## Bitcoin - Anatomía de las transacciones + +### Meta-datos importantes (excepto[transacciones en la base de monedas](https://bitcoin.org/en/glossary/coinbase-transaction)) + +![Bitcoin](img/bitcoin-en-tx-overview.svg) + +- ID de transacción (global) +- Número de versión (evolución del protocolo) +- Hora de cierre + - La primera vez que se puede añadir TX a la cadena de bloques + - Transacciones con bloqueo temporal que sólo son válidas en el futuro. + - Cancelaciones + +-- + +## Bitcoin - Anatomía de las transacciones + +### Entradas y salidas + +![](img/bitcoin-en-tx-overview.svg) + +- Resultado(s) : Índice de arreglo implícito + * Cantidad (satoshis) + * Guión Pubkey ( Desbloquear para gastar) +- Insumos(s) + * Salida gastada (ID de transacción + Índice de salida) + * Número de secuencia (relacionado con la hora de cierre) + * Script de firma (parámetros para desbloquear el script Pubkey) + +> Bitcoin es un libro de contabilidad de distribución pública. + +-- + +## Bitcoin - Transacción de muestra + + blocktrail.com + +![Bitcoin](img/bitcoin.tx.c60e4dc5e69c19ff53a45954d8a8996fd9aac6fda317fd7238dec6a482c718cf.png) + +-- + +## Bitcoin - Envío de transacciones + +##### Configuración de pago a clave pública (P2PKKH) + +![Bitcoin](img/bitcoin-en-crear-p2pkh-output.svg) + +- Curva (elíptica) ECDSA secp256k1 + - Generación de claves públicas determinantes (hash) + +-- + +## Bitcoin - Envío de transacciones + +##### Configuración de pago a hash de clave publica (P2SH) + +![](img/bitcoin-en-crear-p2sh-output.svg) + +- Redimir el hash del script en lugar del hash de la clave pública + * Soporta [PubKey scripts opcodes](https://bitcoin.org/eb/developer-reference#opcodes) + +-- + +## Bitcoin - Envío de transacciones + +###### Finalize TX + +![](img/bitcoin-en-tx-overview-utxo.svg) + +- El remitente crea UTXO con el script PubKey + * ... usando el hash de clave pública del receptor +- Transacción de emisiones del remitente (red P2P) +- Los mineros lo añaden a un bloque (... más detalles más adelante...) +- Cartera : Cantidad de UTXO como saldo utilizable + +-- + +## Bitcoin - Gastar salidas P2PKH + +![](img/bitcoin-en-unlocking-p2pkh-output.svg) + +- ID de transacción de búsqueda e índice para UTXO +- El remitente crea la entrada de transmisión y también agrega: + * Número de secuencia + * Firma y PubKey (script params) + +-- + +## Bitcoin - Gastar salidas P2SH + +![](img/bitcoin-en-unlocking-p2sh-output.svg) + +- ID de transacción de búsqueda e índice para UTXO +- El remitente crea la entrada de transmisión y también agrega: + * Número de secuencia + * Firma y PubKey (script params) + +-- + +## Bitcoin - Salidas de gastos + +###### Last steps + +- El remitente prepara el UTXO para el destinatario (como antes) +- Transacción de emisiones del remitente (red P2P) +- Los mineros lo añaden a un bloque + - Validación del guión ( A-ha!) +- Cartera : Actualizar saldo + +-- + +## Bitcoin - Script público P2PKH estándar + +##### Línea de tiempo de la pila de ejecución + +![](img/bitcoin-en-p2pkh-stack.svg) + +--- + +# Red P2P + +Un monstruo muy peculiar + +-- + + +## Red P2P + +##### Descubrimiento entre iguales - DNS de semillas de Bitcon + +``` +SECCIÓN DE PREGUNTAS +;semilla.bitcoin.sipa.be IN A + +SECCIÓN DE RESPUESTAS +semilla.bitcoin.sipa.be. 60 EN UN 192.0.2.113 +semilla.bitcoin.sipa.be. 60 EN UN 198.51.100.231 +semilla.bitcoin.sipa.be. 60 EN UN 203.0.113.183 +``` + +- Conecte al puerto `8333` (red principal) o `18333` (red de prueba) +- Seguido de mensajes `addr` que anuncian las direcciones de los compañeros + +-- + +## Red P2P + +##### Conectando con sus pares + +- Enviar [mensaje `version`](https://bitcoin.org/en/developer-reference#version) + * número de versión local, bloque y hora actual +- El par responde con su propio mensaje de "versión +- Enviar `getaddr` y recibir `addr` de nuevos pares (descubrimiento) + +-- + +## Red P2P + +##### Transacciones de radiodifusión + +- Envíe [mensaje de invitación](https://bitcoin.org/en/developer-reference#inv) a un par. +- Esperar el mensaje `getdata` +- Enviar datos de la transacción en un mensaje `tx`. +- Los pares reenvían transacciones a otros pares +- Los nodos completos realizan un seguimiento de las transacciones no confirmadas en [memory pool](https://bitcoin.org/en/developer-guide#memory-pool) + +> ...continuará... + +--- + +## El enfoque de la máquina de estado + +- Implantar réplicas del software +- Recibir las solicitudes de los clientes (es decir, las entradas) +- Ordenar las entradas +- Ejecute la transición de SM una y otra vez +- Supervisar las réplicas en busca de diferencias de estado o de salida. + +--- + +## El enfoque de la máquina de estado + +##### Pedido de entradas + +- Soluciones mutiple +- [Blockchain](https://en.wikipedia.org/wiki/Blockchain_database) ? +- Transacciones Bitcoin! + +-- + +## Bitcoin - Gastos de transacción + +![](img/bitcoin-en-tx-overview-spending.svg) + +Ordenamiento causal : Cadena de propiedad + +--- + +## El enfoque de la máquina de Estado + +- Implantar réplicas del software +- Recibir las solicitudes de los clientes (es decir, las entradas) +- Pedir las entradas +- Ejecutar la transición de SM una y otra vez. +- Supervisar las réplicas en busca de diferencias de estado o de salida. + +--- + +## El enfoque de la Máquina de Estado + +##### Ejecutar la Máquina de Estado + +![](img/rsm.transition.png) + +- Ejecutar las entradas en el orden seleccionado en cada réplica. + +-- + +## Bitcoin - Propagación de transacciones + +![](img/bitcoin-en-transaction-propagation.svg) + +--- + +## Bitcoin blockchain + +##### Metas de diseño + +- Libro mayor público + - Transacciones ordenadas y con sello de tiempo +- Almacenamiento distribuido sobre Bitcoin [nodos completos](https://bitcoin.org/en/glossary/node) +- Proteger contra + - [double spending](https://bitcoin.org/en/glossary/double-spend) + - modificación de registros de transacciones anteriores + +-- + +## Bitcoin blockchain + +###### Panorama general + +![](img/bitcoin-en-blockchain-overview.svg) + +-- + +## Cabecera del bloque Bitcoin + +- **Versión**: 4 bytes +- **Características de la cabecera del bloque anterior**: 32 bytes +- **Hash de raiz Merkle**: 32 bytes +- **Tiempo**: 4 bytes +- **nBits**: 4 bytes +- **nonce**: 4 bytes + +-- + +## Bitcoin Bloque 493387 + + blocktrail.com + +[![](img/bitcoin.block.493387.png)](https://www.blocktrail.com/BTC/block/000000000000000000ad396808fdc05052655d8a80aee7ffc538b71828ea03d3) + +-- + +## Bitcoin Block 493387 - Transacciones + +La transacción de Coinbase es lo primero + +[![](img/bitcoin.txs.493387.png)](https://www.blocktrail.com/BTC/block/000000000000000000ad396808fdc05052655d8a80aee7ffc538b71828ea03d3) + +--- + +## Proofs + +- Métrico + * Demostrar interés legítimo, irreversibilidad + * Tomar decisiones sobre cambios en un DApp +- Modificar bloques pasados es más difícil que añadir nuevos bloques. +- Ejemplos comunes + * **Prueba de trabajo** (PoW) + * **Prueba de participación** (PoS) + * **Prueba de espacio** (PoSpace) + * **Prueba de colaboración** (PoC) + * **Prueba de réplica** (PoR) +- Se puede utilizar en paralelo + * p.ej.[PeerCoin](http://peercoin.net) se basa en PoW + PoS + +-- + +## Prueba de trabajo + +- *Conductor* . : Cantidad de trabajo computacional (CPU, GPU, NPU,...) que contribuyó al funcionamiento del DApp. +- Recursos intensos (energía, refrigeración,...) +- El mecanismo para establecer el consenso a través del PoW se denomina comúnmente minería. + +> *Bitcoin* utiliza este enfoque para su funcionamiento diario. + +-- + +## Proof of stake + +- *Conductor* : nuevas monedas según el número de monedas (stake) que poseas. +- Puede ser abusado por aquellos que tienen suficientes monedas. +- Normalmente se combina con otras pruebas + +> *OmniLayer* se basa en el mecanismo POS. + +-- + +## Prueba de capacidad + +- *Conductor* : asignación de cantidades no triviales de memoria o almacenamiento necesarias para resolver un problema (funciones difíciles de memorizar). +- Alternativa más ecológica al PoW + +> Se utiliza PoStorage en PermaCoin, SpaceMint,[BurstCoin](https://en.wikipedia.org/wiki/Burstcoin) . + +-- + +## Prueba de colaboración + +- Validación colaborativa de nodos (en breve CVNs) + *[Decide](https://chain.fair-coin.org/download/FairCoin2-white-paper-V1.1.pdf) qué nodo crea el siguiente bloque + * Aprobar CVN mediante la firma digital de un dato que contenga la identificación del ganador. + * Con las firmas requeridas, reúna TX y cree un nuevo bloque. +- Sin recompensa (dinero nuevo) por la creación del bloque (cuota pequeña) +- El consumo de energía es bajo (CVNs en una Raspberry3) + +> FairCoin (fork de Bitcoin 0.12) implementa PoC desde el 18 de julio de 2017. + +--- + +## Árbol de Merkle - Transacciones de Recoleccion + +![](img/bitcoin-en-merkle-prune.png) + +**Modos de funcionamiento**: [SPV clients](https://bitcoin.org/en/glossary/simplified-payment-verification) vs[nodo completo](https://bitcoin.org/en/glossary/node) + +--- + +## Red P2P (contd.) + +##### Descarga del bloque inicial + +- Primera ejecución : El nodo sólo contiene[bloque 0](https://bitcoin.org/en/glossary/genesis-block) +- Elija un par remoto (también conocido como nodo de sincronización) +- Descargar desde el bloque 1 a la punta actual de la mejor cadena de bloques del nodo de sincronización + * Bloques primero (hasta la versión 0.9.3) + * Encabezados primero (desde 0.10.0 en adelante) + +--- + +## Bitcoin mining + +- Añadir nuevos bloques a la cadena de bloques +- Dificultar la modificación del historial de traducción +- Estrategias + * Minería en solitario + * Minería colectiva + +--- + +## Minería Bitcoin - Minería en solitario + +![](img/bitcoin-en-solo-mining-overview.svg) + +- Minero genera nuevos bloques por su cuenta +- Reclama completamente el premio de bloqueo y las comisiones de transacción +- Grandes pagos +- Mayor varianza (mayor tiempo entre ellos) + +--- + +## Bitcoin mining - Minería en grupo + +![](img/bitcoin-en-pooled-mining-overview.svg) + +- Grupo de mineros comparte recursos con otros mineros +- Encuentra los bocks más a menudo en los objetivos de bits más fáciles +- Producto compartido entre los mineros + * Correlacionado con la potencia relativa del hash PoW +- Pagos pequeños +- Menor varianza (es decir, menor tiempo entre pagos) + +-- + +## SlushPool + +[slushpool.com/home/](https://slushpool.com/home/) + +![](img/slushpool.png) + + Monedas acuñadas ``+1M BTC` extraídas desde diciembre de 2010. `ZCASH` desde el 20 de abril de 2017 + +-- + +## SlushPool + +###### Hash rate + +![](img/slushpool.hashrate.20171113.png) + +-- + +## SlushPool + +##### Distribución de las tarifas de Hash + +![](img/slushpool.hashratedist.20171113.png) + +-- + +## Bitmain - AntMiner + +[bitmaintech.com](https://bitmaintech.com/) + +![](img/bitmain.antminer.s9.png) + + Monedas acuñadas : `BTC` + +-- + +## Bitmain - AntPool + +[bitmaintech.com](https://bitmaintech.com/) + +![](img/bitmain.antpool.png) + +-- + +## Pool de BTCC + +[pool.btcc.com](https://pool.btcc.com/) + +![](img/btcc.png) + + Monedas acuñadas : `BTC` + +--- + +## Hardware minero Bitcoin + +##### Capacidad instalada - 2017/11/13 + +
![](img/btc.hashrate.20171113.png)
) + +- 6,4 EHash/s, 80.704.290,84 PFLOPS +- 10.000 toneladas métricas de hardware. Suficiente material para construir otra torre Eiffel. + +-- + +## Hardware minero Bitcoin - Energía + +![](img/bitcoin.energía.polvo.asic.jpg) + +Circuitos integrados específicos para aplicaciones específicas, también conocidos como ASIC + +-- + +## Consumo de energía de Bitcoin PoW + +... según[BitcoinEnergyConsumption.com](https://BitcoinEnergyConsumption.com) + +![](img/bitcoin.pow.energy.png) + +- Proyectado para ser comparable al de Dinamarca en 2020 + +--- + +## P2P network (contd.) + +###### Bloqueo de la transmisión - Empuje no solicitado + +- Miner incluye el bloque minado en el nuevo[`block` message](https://bitcoin.org/en/developer-reference#block) +- Miner envía un mensaje a sus pares de nodos completos + +> desde la versión 0.12.0 + +-- + +## Red P2P + +###### Bloque de transmisión - Retransmisión de bloque estándar + +- Método estándar +- Miner envía un mensaje `inv` a todos los pares (SPV y nodo completo) + - Incluye inventario referido al bloque +- **Par BF** ⇒ `getdata` solicitando el bloque completo + - Miner ⇒ Mensaje de `bloque` +- **Par HF** ⇒ `getheaders` (pocos encabezados en la mejor cadena de bloques) + - Miner ⇒ Mensajes de `encabezados` +- **Clientes de SPV** ⇒ `getdata` solicitando un bloque Merkle + - Miner ⇒ `merkleblock` seguido de algunos mensajes `tx`. + +> desde la versión 0.12.0 + +-- + +## Red P2P + +###### Block broadcasting - Anuncio de encabezados directos + +- Se usa si los pares señalan con `sendheaders` durante el cacheo. +- Miner envía un mensaje de `cabecera` desde un nuevo bloque +- **HF peer** ⇒ Validación parcial y envío de `getdata` +- Miner ⇒ `block` o `merkleblock`. + +> desde la versión 0.12.0 + +--- + +## El enfoque de la máquina de estado + +- Implantar réplicas del software +- Recibir las solicitudes de los clientes (es decir, las entradas) +- Pedir las entradas +- Ejecute la transición de SM una y otra vez +- Supervisar las réplicas en busca de diferencias de estado o de salida. + +--- + + +## El enfoque de la máquina de estado + +###### Envío de salidas + +- Cada réplica genera salida + * Las réplicas no defectuosas siempre producirán la misma salida +- Se filtran las salidas defectuosas + * Consenso +- Envío de la salida correcta al cliente + +-- + +## Consenso + +- Consenso de Nakamoto +- [Paxos](https://en.wikipedia.org/wiki/Paxos_%28computer_science%29) +- Sistemas de quórum +- [Raft](https://raft.github.io/) +- [Obelisk](https://blog.skycoin.net/statement/obelisk-the-skycoin-consensus-algorithm/) + +--- + +## Bitcoin - Consenso de Nakamoto + +##### Bifurcación ocasional vs bifurcación extendida + +![](img/bitcoin-en-blockchain-fork.svg) + +- Bloques simultáneos extraídos, los nodos eligen al ganador +- Los compañeros prefieren bifurcaciones con un mayor PoW + * Bifurcacion mas larga + * Altura máxima del bloque: distancia hasta[bloque 0] (https://bitcoin.org/en/glossary/genesis-block) + +-- + +## Bitcoin - Consenso de Nakamoto + +##### Bifurcación suave + +![](img/bitcoin-en-soft-fork.svg) + +- Cuándo? + * Muy a menudo, por ejemplo, mineros concurrentes. + * Las reglas de consenso mejoradas rechazan los bloques que antes eran válidos. + + [UASF](https://bitcoin.org/en/glossary/uasf) flag day vs.[MASF](https://bitcoin.org/en/glossary/uasf) Señalización de la mayoría de las tasas de hash + +-- + +## Bitcoin - Consenso de Nakamoto + +##### Resolución de Bifurcacion suave + +- Eliminar bloques (rancios y huérfanos) en bifurcaciones de bajo POW. +- Iterar sobre las transacciones en bloques rancios y huérfanos + * Descartarlo si TX pertenece a otro bloque de la bifurcacion PoW más alta. + * Moverlo de nuevo a TX mempool de lo contrario + + para ser incluido en un futuro bloque por este minero + + Transmisión (¿opcional?) a la red P2P + +-- + +## Bitcoin - Consenso de Nakamoto + +##### Bifurcacion rígidas + +![](img/bitcoin-en-hard-fork.svg) + +- ¿Cuándo? + * Extender la cadena de bloqueo para prevenir ataques de terceros 51%. + * Consenso mejorado Aceptar los bloques rechazados anteriormente + * Partición de red + +-- + +## Bitcoin - Corolarios de bifurcaciones rígidas + +- Advertencia en [`getnetworkinfo`] (https://bitcoin.org/en/developer-reference#getnetworkinfo) y ejecute el comando `-alertnotify` si está configurado. + * +6 bloques PoW que la mejor cadena válida + * Repetición de bloque y TX con números de versión más altos de lo esperado. +- [Coinbase transaction](https://bitcoin.org/en/glossary/coinbase-transaction) sólo se puede gastar después de 100 bloques. +- [Clientes del SPV](https://bitcoin.org/en/glossary/simplified-payment-verification) pueden ponerse en contacto con diferentes nodos completos + * Descartar cadenas con un PoW más débil + +--- + +## Bitcoin - Balance de clientes + +![](img/bitcoin-en-transaction-propagation.svg) + +Software para billetera: Sumar UTXO para determinar el balance + +--- + +## Tolerancia a fallos (en teoría) + +- Tolerancia para F fallos independientes aleatorios + * errores de memoria, fallo del disco duro, .... + * Requiere réplicas `2F + 1` +- La réplica fallida puede detenerse sin generar salidas + * Sólo se requieren réplicas `F + 1` + * .... ningún sistema existente alcanza este límite +- [Byzantine failures](https://en.wikipedia.org/wiki/Byzantine_fault_tolerance) + * Fallas aleatorias, espurias ⇒ `2F + 1` + * ataques maliciosos e inteligentes ⇒ `3F + 1` + +-- + +## Nodo Bitcoin + +##### Requisitos mínimos + +- Escritorio o portátil (Windows, Mac OS X o Linux) +- 125 GB de espacio en disco duro, 2 GB de RAM +- Internet de banda ancha con upload ≥ 400 Kbps (50 KB/s) + * Conexión no medida, o límites de carga elevados, respetar los límites de carga. + * 100 GB IBD + * ≈ 20 gigabytes de descarga al mes + * Carga de +200 GB al mes +- +6 horas al día con el nodo completo en funcionamiento +- +8 conexiones y pares de sincronización activos + +-- + +## Nodo Bitcoin + +> La mayoría de la gente ordinaria **NO** debería estar ejecutando un nodo completo. +> Necesitamos nodos completos que estén siempre encendidos, que tengan más de 8 conexiones. +> *(si sólo tienes 8, entonces eres parte del problema, no parte de la solución)*, +> y tener una conexión de banda ancha a Internet. + +Gavin Andresen, Jefe Científico de la Fundación Bitcoin, en[Reddit post] (http://www.reddit.com/r/Bitcoin/comments/1scd4z/im_running_a_full_node_and_so_should_you/cdw3lrh?context=3) + +--- + +# Teoría General de DApps + +--- + +## Definición de un DApp - Código abierto + +- Debe funcionar de forma autónoma +- Ninguna entidad que controle la mayoría de sus tokens +- Datos y registros en una cadena de bloques pública y descentralizada. + +> Las aplicaciones **Bitcoin** son de código abierto, ninguna entidad controla Bitcoin y sus registros son abiertos y públicos. + +--- + +## Definición de un DApp - Generación de tokens + +- El propósito de un token es permitir el acceso a la aplicación DApp. +- Debe generar tokens de acuerdo con un algoritmo estándar + - Posiblemente distribuir tokens al inicio de la operación. +- Las fichas deben ser necesarias para el uso de la aplicación. +- Contribución de los usuarios premiados mediante pago en los tokens de la aplicación. + +> Por ejemplo, **Bitcoin** genera bitcoins (tokens) con un algoritmo predeterminado que no se puede modificar. Los Tokens son necesarios para que Bitcoin funcione. Los mineros de Bitcoin son recompensados con bitcoins por sus contribuciones a la seguridad de la red Bitcoin. + +--- + +## Definición de un DApp - Consenso + +- El Protocolo podrá adaptarse en respuesta a + * mejoras propuestas + * retroalimentación del mercado +- Cambios decididos por consenso mayoritario de sus usuarios. + +> Por ejemplo, todos los cambios a **Bitcoin** deben ser aprobados por un consenso mayoritario de sus usuarios a través del mecanismo de prueba de trabajo. + +--- + +## Clasificación de DApps - Tipo I + +##### Según el uso de la cadena de bloque + +- Tienen su propia cadena de bloques. + +*Bitcoin*, *Litecoin* y otras[alt-coins] (https://en.wikipedia.org/wiki/List_of_cryptocurrencies) + +--- + +## Clasificación de DApps - Tipo II + +##### Según el uso de la cadena de bloque + +- Utilice la cadena de bloques de una aplicación descentralizada de tipo I. +- Son protocolos + * Fichas que son necesarias para su función. + +> *OmniLayer* (anteriormente *Master Protocol*) y *Blockstack* son ejemplos de aplicaciones descentralizadas de tipo II. + +-- + +## DApps tipo II + +##### Transacciones de datos nulos de Bitcoin + +- Incrustar datos adicionales en transacciones DApp tipo I +- Bitcoin[OP_RETURN](https://bitcoin.org/en/developer-reference#term-op-return) code + * Rendimientos probables de la poda + * Los mineros de Bitcoin tendrán la opción de podar esos datos. + +> Blockstack es un DApp tipo II + +--- + +## Clasificación de DApps - Tipo III + +##### Según el uso de la cadena de bloque + +- Utilizan el protocolo de una aplicación descentralizada de tipo II. +- Son protocolos y tienen fichas que son necesarias para su función. + +> Las aplicaciones *Omni* (anteriormente *Mastercoin*), y *Blockstack* son ejemplos de aplicaciones descentralizadas de tipo III. + +--- + +## Pasos fundamentales de un DApp + +- Publicación del libro blanco +- Distribución de fichas iniciales +- Delegación de la propiedad + +--- + +## Secciones del informe de DApp + +- Intenciones y objetivos de la DApp +- Planes de distribución de fichas +- Mecanismo para establecer el consenso +- Supervisión del DApp +- Gestión de recompensas de desarrolladores +- Descripción técnica de la DApp + +--- + +## Distribución de fichas - Minería + +- Los tokens se distribuyen a aquellos que contribuyen con más trabajo a la operación de un DApp. + +> Tomando como ejemplo *Bitcoin*, las bitcoins se distribuyen mediante un algoritmo predeterminado a los mineros que verifican las transacciones y mantienen la cadena de bloques Bitcoin. + +--- + +## Distribuir de tokens - Recaudación de fondos + +- Los tokens se distribuyen a quienes financian el desarrollo inicial del DApp. + +> Tomando como ejemplo el *Master Protocol*, Mastercoins se distribuyó inicialmente a aquellos que enviaban bitcoins a una dirección determinada a razón de 100 Mastercoins por bitcoin enviado. Las bitcoins recolectadas se utilizaron para financiar el desarrollo de aplicaciones que promovieron el desarrollo del Protocolo Maestro. + +--- + +## Distribución de tokens - Desarrollo + +- Los tokens se generan utilizando un mecanismo predefinido y sólo están disponibles para el desarrollo del DApp. + +> Además de su mecanismo de recaudación de fondos, el Protocolo Maestro utilizó el mecanismo de colaboración para financiar su desarrollo futuro. Algunas Mastercoins se distribuyen a través de un sistema de recompensas impulsado por la comunidad y basado en el mecanismo PoS. + +--- + +# Blockstack + +--- + +## ¿Por qué Blockstack? + +Internet ya tiene más de 40 años + +- [Servicios críticos fuera de línea](https://www.wired.com/2016/10/internet-outage-ddos-dns-dyn/) por ataques como DDoS en servidores DNS +- Confianza implícita, por ejemplo, [TurkTrust CA emitió certificados de seguridad falsos para Google](http://cnet.co/2oArU6O) +- De escritorio a nube crea SPoF, por ejemplo [Yahoo! perdiendo datos para 500 millones de personas](http://nyti.ms/2oAqn0G.) + +-- + +## ¿Por qué Blockstack? + +##### Ryan Shea, cofundador de Blockstack + + + +--- + +## ¿Qué es Blockstack? + +- Un nuevo Internet para aplicaciones descentralizadas +- Código abierto +- Re-descentralizar Internet +- Los usuarios poseen sus datos + +-- + +## Principio de diseño de confianza a confianza + +##### Muneeb Ali, Director Técnico de Blockstack + + + +--- + +## Metas Blockstack + +- Nombramiento y Descubrimiento Descentralizado + - Registrarse y utilizar nombres legibles por personas + - Descubra los recursos de red sin tener que confiar en ninguna parte remota. +- Almacenamiento descentralizado + - Almacenar datos sin revelarlos a terceros remotos. +- Rendimiento comparable + +--- + +## Blockstack - Decisiones clave + +- Sobrevivir a las fallas de las cadenas de bloqueo subyacentes +- Mantenga la complejidad y la lógica fuera de las cadenas de bloqueo + - opuesto a NameCoin, Ethereum, etc. ... +- Índice escalable para datos globales + +--- + +## Arquitectura Blockstack + +![](img/bsk-arquitectura-diagrama5.png) + +--- + +## Blockstack layers + +- Cadena de bloques virtual, encima de la cadena de bloques Bitcoin +- *Atlas*, una red de pares + - Índice global de información de descubrimiento +- **Gaia**, sistema de almacenamiento descentralizado + +> Los usuarios no necesitan confiar en ninguna capa de datos . + +--- + +## Blockstack - Capa de cadena de bloques + + DApp tipo II + +![](img/blockstack.blocks.png) + +-- + +## Blockstack - Transacciones de Nameops + +[![](img/blockstack.nameops.49393935.png)](https://explorer.blockstack.org/nameops/493935) + +-- + +## Ejemplo de transacción de datos nulos de Blockstack + + NAME_REGISTRATION bluestack.id + +[![](img/bitcoin.tx.702e76497a6061222208698c4d0fbed6ca768d10832e1b8da9184a8ea6f5ded8.png)](https://www.blocktrail.com/BTC/tx/702e76497a6061222208698c4d0fbed6ca768d10832e1b8da9184a8ea6f5ded8) + +--- + +## Blockstack - Capa de cadena virtual + +###### ¿Por qué? + +- RSM coherentes con la bifurcacion* en las cadenas de bloques existentes +- Detección y recuperación de bifurcaciones +- Migración a través de la cadena + - [Razones](https://blockstack.org/blog/why-blockstack-is-migrating-to-the-bitcoin-blockchain) para que Blockstack migre de Namecoin a Bitcoin + +-- + +## Blockstack - Capa de cadena virtual + +##### ...de acuerdo con Muneeb Ali, Director Técnico de Blockstack. + + + +-- + +## Blockstack - Cadena virtual + +##### Filtrando y ordenando TXs de OP_RETURN + + ![](img/bsk-virtual-blockchain.png) (en inglés) + +--- + +## Aplicaciones Blockstack - Explorer y AppStore + +![](img/bsk-appstore.png) + +--- + +## Aplicaciones Blockstack - Clonación de iTunes + +![](img/bsk-app-itunes.png) + +--- + +## Aplicaciones Blockstack - Afia + +![](img/bsk-app-afia.png) + +--- + +## Aplicaciones Blockstack - Casa + +![](img/bsk-app-casa.png) + +--- + +## Winding Up + +- Gracias por venir! +- Nos encantaría conocer su opinión: [bit.ly/blockstack-cuba-feedback](http://bit.ly/blockstack-cuba-feedback) \ No newline at end of file diff --git a/dapps.md b/dapps.md index 8174d07837e..8bdbecd9c18 100644 --- a/dapps.md +++ b/dapps.md @@ -229,7 +229,7 @@ Password: meet-ups - Sender prepares UTXO for recipient (as before) - Sender broadcasts transaction (P2P network) - Miners add it to a block - * Script validation ! ( A-ha! ) + - Script validation ! ( A-ha! ) - Wallet : Update balance -- @@ -898,7 +898,7 @@ Gavin Andresen, Bitcoin Foundation’s Chief Scientist, in [Reddit post](http:// - Tokens are generated using a predefined mechanism and are only available for the development of the DApp. -> In addition to its fund-raising mechanism, the Master Protocol used the collaboration mechanism to fund its future development. Some Mastercoins are distributed via a community-driven bounty system based on the PoS mechanism. +> In addition to its fund-raising mechanism, the Master Protocol used the collaboration mechanism to fund its future development. Some Mastercoins are distributed via a community-driven bounty system based on the PoS mechanism. --- @@ -911,8 +911,8 @@ Gavin Andresen, Bitcoin Foundation’s Chief Scientist, in [Reddit post](http:// The Internet is +40 years old now - [Critical services offline](https://www.wired.com/2016/10/internet-outage-ddos-dns-dyn/) by attacks like DDoS on DNS servers -- Implicit trust e.g. [TurkTrust CA issued false security certificates for Google](http: //cnet.co/2oArU6O) -- Desktop to cloud creates SPoF e.g. [Yahoo! losing data for 500M people](http: //nyti.ms/2oAqn0G.) +- Implicit trust e.g. [TurkTrust CA issued false security certificates for Google](http://cnet.co/2oArU6O) +- Desktop to cloud creates SPoF e.g. [Yahoo! losing data for 500M people](http://nyti.ms/2oAqn0G.) -- diff --git a/gobot-es.md b/gobot-es.md new file mode 100644 index 00000000000..7c14c32d5e4 --- /dev/null +++ b/gobot-es.md @@ -0,0 +1,929 @@ +# Taller de gobots + +#### Estas diapositivas: [slides.cuban.tech/gobot.html](http://slides.cuban.tech/gobot.html) + +---------------- + +### Información Wifi + +Red: cubantech + +Contraseña: meet-ups + +---------------- + +### Si aún no lo has hecho, instala Go + +- [Descargar Go](https://golang.com/) + +- [Descargar Go desde LAN](ftp://qnap01.local/Public/soft/go) + +## Nuestras pautas de la comunidad + +[Ser excelente el uno con el otro](https://github.com/nodeschool/havana/blob/master/Code_of_Conduct.md) + +--- + +Próximos Eventos CubanTech + +- [CubanTech meetups](http://meetup.cuban.tech) +- [Encuentros en Cuba](http://docker.cuban.tech) +- [Blockstack Cuba meetups](http://blockstack.cuban.tech) +- [SciPyLA 2018](http://scipyla.org/conf/2018) + * Universidad de Sancti Spiritus, 22-25 de noviembre de 2017. + +--- + +# Enorme gracias a nuestro anfitrión + +--- + +## ¿Qué son los gobots? + +![](img/gobot.png) + +--- + +## Golang + Robots = Gobots + +--- + +# ¡Comencemos! + +--- + +## Nuestro hardware + +[![](img/hardware-kit-closed.jpg)](http://www.seeedstudio.com/depot/ARDX-The-starter-kit-for-Arduino-p-1153.html) + +--- + +## Nuestro hardware + +[![](img/hardware-kit-open.jpg)](http://www.seeedstudio.com/depot/ARDX-The-starter-kit-for-Arduino-p-1153.html) + +--- + +## A los kits les puede faltar equipo + +------------ + +Si tiene problemas para encontrar un componente, háganoslo saber y le conseguiremos un reemplazo. + +--- + +## ¿No funciona? + +## ¡Probablemente hardware! + +--- + +## Componentes que estamos cubriendo + +- LEDs (diodos emisores de luz) +- Botones +- Servos + +--- + +Siéntase libre de seleccionar los componentes que más le gusten y completar los retos que más le interesen. + +--- + +# Empezando + +-- + +## Instalar Go si aún no lo has hecho + +[Descargar Go de Internet](https://golang.org/) + +[Descargar Go de LAN](ftp://qnap01.local/Public/soft/go) + +-- + +## Crear directorio de proyectos + +```sh +mkdir gobots +cd gobots +``` + +-- + +## Instalar Gobot + +```sh +go get -d -u gobot.io/x/gobot/.... +``` + +--- + +# Empezando + +## Firmata estándar + +- Permite a Gobot comunicarse con el Arduino a través de USB +- La mayoría de los Arduinos ya tienen instalados los Firmatas Estándar de talleres anteriores +- Vamos a comprobar que tu Arduino ya tiene instalado el Firmata Estándar! + +--- + +## Conecta el arduino + +![](img/connecting-arduino.jpg) + +--- + +Crear el fichero + +1. Ve a tu directorio de gobots +2. Cree un archivo llamado test.go +3. Copie el código que aparece a continuación y guarde + +```go +package main + +import ( + "time" + "gobot.io/x/gobot" + "gobot.io/x/gobot/drivers/gpio" + "gobot.io/x/gobot/platforms/firmata" +) + +func main() { + + firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0"); + led := gpio.NewLedDriver(firmataAdaptor, "13"); + + work := func() { + + gobot.Every(1 * time.Second, func() { + + led.Toggle(); + + }); + + }; + + robot := gobot.NewRobot("bot", + []gobot.Connection{firmataAdaptor}, + []gobot.Device{led}, + work, + ); + + robot.Start(); + +} +``` + +--- + +Ejecute el código + +```sh +go run test.go +``` + +--- + +## Este LED debería estar parpadeando cada 1 segundo + +![](img/built-in-led.png) + +--- + +Si funciona, ¡continúe! → + +------------ + +Si no es así, pulsa ↓ para obtener instrucciones sobre cómo flashear tu Arduino con Firmata Estándar + +-- + + +## Cómo flashear tu Arduino con Firmata estándar (Plus) + +1. Descargue el[Arduino IDE](https://www.arduino.cc/en/main/software) +2. Asegúrate de que tu Arduino está conectado vía USB +3. Abra el IDE de Arduino +4. Seleccione: `Arhivo > Ejemplos > Firmata > StandardFirmataPlus` +5. Seleccione: `Herramientas > Placa > Arduino/Genuino Uno` +6. Seleccione: `Herramientas > Puerto > ` +7. Haga clic en el botón Upload ![](img/arduino-ide-upload-button.png) +8. Vuelva a intentar hacer que el LED parpadee + +--- + +## Componentes que estamos cubriendo + +- LEDs (diodos emisores de luz) +- Botones +- Servos + +--- + +## LEDs + +#### LIGHT EMITTING DIODES + +![](img/leds.jpg) + +--- + +## Pines LED de identificación + +- La clavija larga es positiva (y se pone en marcha) +- El pin corto es negativo (y va a tierra) + +![](img/led-pin-diagram.png) + +--- + +## Construya esto + +![](img/arduino-led.png) + +--- + +Guarde esto en un archivo y ejecútelo + +```go +package main + +import ( + "time" + "gobot.io/x/gobot" + "gobot.io/x/gobot/drivers/gpio" + "gobot.io/x/gobot/platforms/firmata" +) + +func main() { + + firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0"); + led := gpio.NewLedDriver(firmataAdaptor, "11"); + + work := func() { + + gobot.Every(500 * time.Millisecond, func() { + + led.Toggle(); + + }); + + }; + + robot := gobot.NewRobot("bot", + []gobot.Connection{firmataAdaptor}, + []gobot.Device{led}, + work, + ); + + robot.Start(); + +} +``` +`node blinky.go` + +--- + +## Si tiene éxito, deberías ver esto + +![](img/blinking-led.gif) + +--- + +## Cambio de la frecuencia de parpadeo + +- Probablemente notó que la luz parpadea cada 0,5 segundos. +- Cambie el código para que parpadee a una velocidad diferente y luego vuelva a ejecutarlo para asegurarse de que funciona. +- Si está atascado, presione ↓ para ver una solución potencial + +-- + +```go +package main + +import ( + "time" + "gobot.io/x/gobot" + "gobot.io/x/gobot/drivers/gpio" + "gobot.io/x/gobot/platforms/firmata" +) + +func main() { + + firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0"); + led := gpio.NewLedDriver(firmataAdaptor, "13"); + + work := func() { + + gobot.Every(3 * time.Second, func() { + + led.Toggle(); + + }); + + }; + + robot := gobot.NewRobot("bot", + []gobot.Connection{firmataAdaptor}, + []gobot.Device{led}, + work, + ); + + robot.Start(); + +} +``` + +`node blinky.go` + +--- + +## Paneles: Cableado sin soldadura + +#### Los paneles nos permiten conectar rápidamente los componentes para hacer prototipos + +![](img/breadboard.small.png) + +--- + +## Paneles: Conexiones eléctricas + +- Aquí puedes ver cómo se conectan las diferentes filas y columnas. +- Si no está claro, no dudes en buscar en Google o pedirle a un voluntario que te lo explique. + +![](img/breadboard-diagram.small.jpg) + +## Usa tu protoboard y un par de cables (el color no importa) para construir esto + +![](img/arduino-led-breadboard.png) + +--- + +Ahora ejecute uno de sus programas anteriores y asegúrese de que el LED siga parpadeando + +--- + + +## Desafíos del LED + +Ahora que tiene los fundamentos de los LEDs, puede pasar al siguiente componente o trabajar en algunos desafíos de los LEDs. + +- Pulse → para pasar al siguiente componente +- Pulse ↓ para desplazarse por los desafíos de los LEDs + +-- + +## Desafíos del LED + +*¡Intenta resolverlos tú mismo antes de mirar la solución!* + +Pulse ↓ para desplazarse por los siguientes retos (y posibles soluciones) + +1. Múltiples luces +2. Contador binario + +-- + +### 1. Múltiples luces + +Haga que 2 (o más) luces se alternen parpadeando + +![](img/alternate-blinking.gif) + +-- + +### Solución Potencial de Múltiples Luces - Hardware + +![](img/alternate-blinking-hardware.png) + +-- + +### Solución Potencial de Múltiples Luces - Código + +```go +package main + +import ( + "time" + "gobot.io/x/gobot" + "gobot.io/x/gobot/drivers/gpio" + "gobot.io/x/gobot/platforms/firmata" +) + +func main() { + + firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0"); + led1 := gpio.NewLedDriver(firmataAdaptor, "13"); + led2 := gpio.NewLedDriver(firmataAdaptor, "12"); + + work := func() { + + first := true + + gobot.Every(1 * time.Second, func() { + + if first == true { + led1.On(); + led2.Off(); + first = false; + } else { + led1.Off(); + led2.On(); + first = true + } + + }); + + }; + + robot := gobot.NewRobot("bot", + []gobot.Connection{firmataAdaptor}, + []gobot.Device{led1, led2}, + work, + ); + + robot.Start(); + +} +``` + +-- + +### Solución de contador binario potencial (isaacvr) - Código + +```go +package main + +import ( + "time" + "gobot.io/x/gobot" + "gobot.io/x/gobot/drivers/gpio" + "gobot.io/x/gobot/platforms/firmata" +) + +func main() { + + firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0"); + led1 := gpio.NewLedDriver(firmataAdaptor, "13"); + led2 := gpio.NewLedDriver(firmataAdaptor, "12"); + led3 := gpio.NewLedDriver(firmataAdaptor, "11"); + led4 := gpio.NewLedDriver(firmataAdaptor, "10"); + + ledList := []*gpio.LedDriver{ led1, led2, led3, led4 } + + work := func() { + + var cnt int = 0 + var aux int = 0 + var val int = 0 + + gobot.Every(1 * time.Second, func() { + + if cnt == 16 { + cnt = 0 + } + + aux = cnt + + for _, led := range ledList { + val = aux % 2 + if val == 1 { + led.On() + } else { + led.Off() + } + aux = aux / 2 + } + + cnt = cnt + 1 + + }); + + }; + + robot := gobot.NewRobot("bot", + []gobot.Connection{firmataAdaptor}, + []gobot.Device{led1, led2, led3, led4}, + work, + ); + + robot.Start(); + +} +``` + +-- + +### Solución binaria alternativa para el contador (olemis) - Código + +```go + +package main + +import ( + "time" + "gobot.io/x/gobot" + "gobot.io/x/gobot/drivers/gpio" + "gobot.io/x/gobot/platforms/firmata" +) + +func main() { + firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0") + leds := []*gpio.LedDriver { + gpio.NewLedDriver(firmataAdaptor, "3") + gpio.NewLedDriver(firmataAdaptor, "5") + gpio.NewLedDriver(firmataAdaptor, "10") + gpio.NewLedDriver(firmataAdaptor, "12") + } + + counter := 0 + + work := func () { + for _, led := range leds { + led.Off() + } + + gobot.Every(1 * time.Second, func() { + mask := 1 + for _, led := range leds { + if mask & counter == 0 { + led.Off() + } else { + led.On() + } + mask = mask << 1 + } + counter++ + }) + } + + robot := gobot.NewRobot("bot", + []gobot.Connection{firmataAdaptor}, + []gobot.Device{leds[0], leds[1], leds[2], leds[3]}, + work, + ); + + robot.Start(); + +} + +``` + +--- + +## Botones + +![](img/buttons.jpg) + +--- + +## Build This + +![](img/button-hardware.png) + +--- + +## Guarda esto en un archivo y ejecútalo + + +```go +package main + +import ( + "fmt" + "gobot.io/x/gobot" + "gobot.io/x/gobot/drivers/gpio" + "gobot.io/x/gobot/platforms/firmata" +) + +func main() { + + firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0"); + button := gpio.NewButtonDriver(firmataAdaptor, "2") + led := gpio.NewLedDriver(firmataAdaptor, "13") + + work := func() { + + button.On(gpio.ButtonPush, func(data interface{}) { + led.On(); + fmt.Println("Button Pressed!"); + }); + + button.On(gpio.ButtonRelease, func(data interface{}) { + led.Off(); + fmt.Println("Button Released!"); + }); + + }; + + robot := gobot.NewRobot("bot", + []gobot.Connection{firmataAdaptor}, + []gobot.Device{button, led}, + work, + ); + + robot.Start(); + +} +``` + +`go run button.go` +--- + +Intente presionar, soltar y mantener presionado el botón + +Deberías ver alguna salida como esta en la consola + +``` + +>> Botón pulsado! +Botón liberado! +Botón pulsado! +Botón liberado! +Botón pulsado! +Botón liberado! +``` + +--- + +El LED debe encenderse al presionar y apagarse al soltarlo. + +--- + +## Desafíos de los botones + +Ahora que tiene los conceptos básicos de los botones, puede pasar al siguiente componente o trabajar en algunos desafíos de botones. + +- Pulse → para pasar al siguiente componente +- Presione ↓ para desplazarse por los desafíos del botón + +-- + +## Desafíos de los botones + +*¡Intenta resolverlos tú mismo antes de mirar la solución!* + +Pulse ↓ para desplazarse por los siguientes retos (y posibles soluciones) + +1. Interruptor de luz +2. Luces navideñas +3. Clave de acceso + +-- + +### 1. Interruptor de luz + +Haga que al presionar un botón alternativamente encienda y apague un LED + +-- + +### Solución de interruptor de luz potencial - Hardware + +![](img/light-switch-hardware.png) + +-- + +### Solución de interruptor de luz potencial - Código + +```go +package main + +import ( + "fmt" + "gobot.io/x/gobot" + "gobot.io/x/gobot/drivers/gpio" + "gobot.io/x/gobot/platforms/firmata" +) + +func main() { + + firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0"); + button := gpio.NewButtonDriver(firmataAdaptor, "2") + led := gpio.NewLedDriver(firmataAdaptor, "13") + + work := func() { + + isOn := false; + + button.On(gpio.ButtonPush, func(data interface{}) { + if isOn == true { + led.Off(); + isOn = false; + } else { + led.On(); + isOn = true + } + }); + + }; + + robot := gobot.NewRobot("bot", + []gobot.Connection{firmataAdaptor}, + []gobot.Device{button, led}, + work, + ); + + robot.Start(); + +} +``` + +-- + +## Componentes que estamos cubriendo + +- LEDs (diodos emisores de luz) +- Botones +- Servos + +--- + +## SERVOS + +![](img/servo.jpg) + +--- + +Toma tu servo y añádele uno de los adjuntos. + +![](img/servo.jpg) + +--- + +## Construya esto + +![](img/servo-hardware.png) + +--- + +## Servo Challenges + +Ahora puedes pasar al siguiente componente, o trabajar en algunos desafíos de servo + +Pulse → para pasar al siguiente componente +Pulse ↓ para desplazarse por los desafíos de los servos + +-- + +## Servo Challenges + +*¡Intenta resolverlos tú mismo antes de mirar la solución!* + +Pulse ↓ para desplazarse por los siguientes retos (y posibles soluciones) + +1. Apersor +2. Flechas +3. Botón + +-- + +### 1. Rociador + +Haz que el servo gire de un lado a otro como si fuera un aspersor. + +![](img/sprinkler.gif) + +-- + +### Solución potencial de aspersor - Hardware + +![](img/sprinkler-hardware.png) + +-- + +### Solución potencial de aspersor - Código + +```go +package main + +import ( + "time" + "gobot.io/x/gobot" + "gobot.io/x/gobot/drivers/gpio" + "gobot.io/x/gobot/platforms/firmata" +) + +func main() { + + firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0") + servo := gpio.NewServoDriver(firmataAdaptor, "11") + + work := func() { + + var angle uint8 = 0; + var max uint8 = 180; + + servo.Move(angle) + + gobot.Every(500 * time.Millisecond, func() { + + angle = (angle + 45) % max + + servo.Move( angle ) + + }); + + } + + robot := gobot.NewRobot("servoBot", + []gobot.Connection{firmataAdaptor}, + []gobot.Device{servo}, + work, + ) + + robot.Start() + +} +``` + +-- + +### 2. Flechas + +Haz que al presionar el botón de flecha izquierda gire el servo en una dirección y al presionar el botón de flecha derecha gire en la otra dirección. + +![](img/servo-arrows.gif) + +-- + +### Solución de Flechas Potenciales - Hardware + +![](img/servo-arrows-hardware.png) + +-- + +### Solución de flechas potenciales - Código + +```go +package main + +import ( + "gobot.io/x/gobot" + "gobot.io/x/gobot/drivers/gpio" + "gobot.io/x/gobot/platforms/firmata" + term "github.com/nsf/termbox-go" +) + +func reset() { + term.Sync() +} + +func main() { + + err := term.Init(); + + if err != nil { + panic(err) + } + + defer term.Close() + + firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0") + servo := gpio.NewServoDriver(firmataAdaptor, "11") + + work := func() { + + var angle uint8 = 0; + + servo.Move(angle) + + for { + reset(); + switch ev := term.PollEvent(); ev.Type { + case term.EventKey: + switch ev.Key { + case term.KeyArrowLeft: + angle = 0 + servo.Move(angle) + case term.KeyArrowRight: + angle = 180 + servo.Move(angle) + } + } + } + + } + + robot := gobot.NewRobot("servoBot", + []gobot.Connection{firmataAdaptor}, + []gobot.Device{servo}, + work, + ) + + robot.Start() + +} +``` + +-- + +Uh oh oh! Nos acabamos las diapositivas! Siéntase libre de probar algunos de los otros componentes de su kit mientras nosotros añadimos más! + +--- + +## Winding Up + +- Gracias por venir! \ No newline at end of file diff --git a/gobot.md b/gobot.md index ed4589e2ef5..92ea63e313d 100644 --- a/gobot.md +++ b/gobot.md @@ -227,7 +227,7 @@ If not, press ↓ for instructions on flashing your Arduino with Standard Fir ## LEDs -#### LIGHT EMITTING DIODES +LIGHT EMITTING DIODES ![](img/leds.jpg) diff --git a/index-es.md b/index-es.md new file mode 100644 index 00000000000..8a896e7fe81 --- /dev/null +++ b/index-es.md @@ -0,0 +1,110 @@ +# Reuniones CubanTech + +## [meetup.cuban.tech](http://meetup.cuban.tech) + +- [Introducción al taller de PyDay Django parte 3](intro_20180729.html) + - [CubanTech Encuentro #37](http://docker.cuban.tech/events/251517589/) - La Habana, Cuba 2018/07/29 +- [Bienvenido a Raspberry Jam](intro_2018080303.html) + - [CubanTech Encuentro #31](http://meetup.cuban.tech/events/247616068/) - La Habana, Cuba 2018/03/03 +- [Introducción a la reunión de Neo4J PyDay](intro_20180113.html) + - [CubanTech Encuentro #28](http://meetup.cuban.tech/events/246212946/) - La Habana, Cuba 2018/01/13 +- [Introducción a PyDay y reunión de cumpleaños #1](intro_20171222.html) + - [CubanTech Encuentro #26](http://meetup.cuban.tech/events/245032996/) - La Habana, Cuba 2017/12/22 + +---------------- + +## Reuniones CubanTech + +### [meetup.cuban.tech](http://meetup.cuban.tech) + +- [Introducción a Blockstack Cuba Encuentro #1](intro_20171119.html) + *[Blockstack Cuba Encuentro #1](http://blockstack.cuban.tech/events/244120891/) - La Habana, Cuba 2017/11/19 +- [Introducción a las reuniones](intro_20170121.html) + *[CubanTech Encuentro #17](http://docker.cuban.tech/events/241708287/) - Isla de la Juventud, Cuba 2017/08/19 + *[CubanTech Encuentro #4](http://docker.cuban.tech/events/236654894/) - Santa Clara, Cuba 2017/01/21 + +--- + +[![Docker Cuba](img/dockercuba.logo.png)](http://docker.cuban.tech) + +## [docker.cuban.tech](http://docker.cuban.tech) + +-- + +- [Introduccion a Docker Celebración del Cumpleaños #4](intro_20170304.html) + *[CubanTech Encuentro #8](http://docker.cuban.tech/events/238007254/) - La Habana, Cuba 2017/03/04 +- [Introducción a Docker para programadores y DevOps](docker-intro.html) + - Conferencia inaugural y laboratorios para el Festival de Software, Universidad de Sancti Spiritus, Cuba 2017/03/21 +- [Laboratorio practico de Docker para dispositivos ARM IoT - Raspberry Pi & ODROID](docker-stuff/hypriot) + - FLISoL 2017, Joven Club, La Habana, Cuba 2017/04/22 + - [CubanTech Encuentro #14](http://docker.cuban.tech/events/240871128/) - Tutorial práctico de Hypriot Joven Club, Cienfuegos, Cuba 2017/06/16 + *[CubanTech Encuentro #15](http://docker.cuban.tech/events/240872505/) - Tutorial práctico de Hypriot, La Habana, Cuba 2017/07/22 + +--- + +[![Python Cuba](img/python-logo.png)](http://pythoncuba.org) + +## PYTHON CUBA + +### Siga Nuestro [meetups](http://meetup.cuban.tech) + +-- + +- Estado de Python . Aplicaciones + - PyDay #1 , La Habana +- Introducción a Brython. Ejemplo de aplicación Tizen + - Joven Club, Cienfuegos, Cuba +- [Introducción a MicroPython en ESP8266](micropython.html) + - [CubanTech Encuentro #13](http://meetup.cuban.tech/events/240871291/) - PyDay Joven Club, Cienfuegos, Cuba 2017/06/16 + - [CubanTech Encuentro #19](http://meetup.cuban.tech/events/242499554/) - PyDay Isla de la Juventud, Cuba 2017/08/20 +- [Python y Pandas para periodismo de datos](pandas-ddj.html) + - [CubanTech Encuentro #16](http://meetup.cuban.tech/events/240372001/)- PyDay La Habana Cuba 2017/07/29 + +--- + +## NODEBOTS CUBA + +### Siga Nuestro [meetups](http://meetup.cuban.tech) + +-- + +- [Nodebots con CubanTech](nodebots.html) + - [CubanTech Encuentro #3](#) - Holguía Cuba 2016/12/25 + - [CubanTech Encuentro #18](http://meetup.cuban.tech/events/241706888/) - Isla de la Juventud Cuba 2017/08/21 + - [CubanTech Encuentro #20](http://meetup.cuban.tech/events/242652841/) - La Habana Cuba 2017/08/26 + +--- + +## SKYFLEET MEETUPS + +### Siga Nuestro [meetups](http://meetup.cuban.tech) + +-- + +- [Blockchain, DApps y Skycoin](skycoin.intro.html) + - [CubanTech Encuentro #35](http://meetup.cuban.tech/events/251519052) - La Habana, Cuba, 2018/06/16 + - [CubanTech Encuentro #36](http://meetup.cuban.tech/events/251523453) - Isla de la Juv., Cuba, 2018/07/02 +- [Explicación de la API de REST de Skycoin](skycoin.libs.html) + - [CubanTech Encuentro #52](http://meetup.cuban.tech/events/259974015) - La Habana, Cuba, 06/04/2010 + +--- + +## BLOCKSTACK CUBA + +### [blockstack.cuban.tech](http://blockstack.cuban.tech) + +-- + +- [Blockchain, DApps y Blockstack](dapps.html) + - [Blockstack Cuba Encuentro #1](http://blockstack.cuban.tech/events/244120891), La Habana, Cuba, 2017/11/19 + +--- + +## Los que hacen DIY Cuba + +### Siga Nuestros [meetups](http://meetup.cuban.tech) + +-- + +- [Electrónica digital - parte 1](https://slides.cuban.tech/digital-electronics-1.html) + - [CubanTech Encuentro #45](https://www.meetup.com/CubanTech/events/258279078/) - La Habana, Cuba 2019/01/27 diff --git a/intro_20180303-es.md b/intro_20180303-es.md new file mode 100644 index 00000000000..b078019e8d2 --- /dev/null +++ b/intro_20180303-es.md @@ -0,0 +1,170 @@ + + +## RASPBERRY JAM, LA HABANA 2018 +#### Mermelada Cubana + +---------------- + +#### Estas diapositivas: [slides.cuban.tech/intro_20180113.html](http://slides.cuban.tech/intro_20180113.html) + +------------ + +Autor: Olemis Lang (olemis@cuban.tech) + +Red: cubantech + +Contraseña: meet-ups + +------------ + +#### SOCIALIZANDO TECNOLOGÍAS AVANZADAS DE SOFTWARE LIBRE + +[sitio web cuban.tech](http://cuban.tech) + +--- + +## ¿QUÉ ES EL GRUPO CUBANTECH? + +Un grupo de empresarios cubanos con visión social + +![](img/cubantech.map.png) + +-- + +- Socializar el conocimiento a través de actividades educativas +- Enseñanza de la evolución digital en lenguaje natural y lenguaje de programación +- Promover una red sostenible de cooperación y promoción de la innovación tecnológica cubana +- Un complemento para ayudar a las personas comunes que no programan a introducir la tecnología en sus vidas de forma saludable. + +--- + +## Reglas de los Encuentros + +#### UNA COMUNIDAD LIBRE DE ACOSO PARA TODOS, INDEPENDIENTEMENTE DE: + +- [Código de conducta](https://github.com/nodeschool/havana/blob/master/Code_of_Conduct.md) +- sexo, identidad o expresión de género, orientación sexual, discapacidad, +- apariencia física, edad, tamaño corporal, raza, nacionalidad o creencias religiosas + +-- + +## REGLAS EXTRAS DEL ANFITRION + +- Preservar el lugar, voz baja, etc. + +-- + +## OTRAS REGLAS BÁSICAS PARA UNA EXPERIENCIA ATRACTIVA + +- Respeta el límite de tiempo de tu discurso de apertura. +- Pregunte sin importar cuando, pero POR FAVOR PREGUNTE! +- Comparta con los asistentes todo lo que pueda. + +--- + +## RASPBERRY JAMS + +![](img/rpi.jams.map.201803.png) + +--- + +## GRACIAS! + +- Fundación Raspberry Pi +- Fundación Python Software +- Equipo HypriotOS + +--- + +## ¿TE GUSTA NUESTRO ESTANDARTE? + +![](img/rpi.cuba.banner.png) + +--- + +## AGENDA DE ESTA REUNION + +- ¿Qué es una Raspberry Jam? +- Uso del Raspberry Pi como infraestructura para las reuniones +- Charlas +- Propuestas +- Descanso +- Votar +- Laboratorio práctico: HypriotOS - Docker on ARM Boards[slides](docker-stuff/hypriot) +- Más charlas + +--- + +## RECURSOS + +- Videos [media.cuban.tech](http://media.cuban.tech) + - [Adafruit DIY videos](http://videos.cuban.tech/Adafruit.Liked.videos/) +- [Documentación](ftp://qnap01.local/Public/docs/) + - [Revista MagPi](ftp://qnap01.local/Public/docs/magpi) +- Paquetes Raspbian + - [archive.framberrypi.org/](http://archive.raspberrypi.org/) + - [archive.raspbian.org/](http://archive.raspbian.org/) +- Imágenes del SO + - [HypriotOS images](ftp://qnap01.local/Public/os/hypriot) + - Imágenes Raspberry Pi (... algunas subcarpetas en[aquí](ftp://qnap01.local/Public/os/) ) + +-- + +## Mas Recursos + +- Matriz de habilidades CubanTech[forms.cuban.tech/dev-matrix](http://forms.cuban.tech/dev-matrix) + - Ofertas de empleo... ¡te llamaremos! + +-- + +## PRÓXIMAMENTE + +- El reto de los pronósticos de la Liga de Campeones de la UEFA +- El desafío de las predicciones de la Copa Mundial de la FIFA +- El reto de las predicciones de la final de la NBA + +--- + +## PERSONAS INVITADAS + +--- + +## TEMAS PARA LAS PRÓXIMAS REUNIONES + +- Python y Julia en Física +- Python en bioinformática +- Economía computacional + +-- + +## TTEMAS PARA LAS PRÓXIMAS REUNIONES + +- Cadena de bloques y DApps impulsados por Python +- Realidad virtual y hardware +- Sistemas de información geográfica +- Python en la ciencia +- Presente su idea de proyecto + +--- + +### SCIPYLA 2018 + +##### ¡ Nos vamos para Curitiba! - [Talk in CubanTech meetups](http://forms.cuban.tech/cubantech-speak) + +![](img/scipyla2018.annonce.png) + +--- + +## CANALES DE COMUNICACIÓN + +[CUBAN.TECH](http://cuban.tech) SITIO WEB + +- Twitter [http://twitter.cuban.tech](http://twitter.cuban.tech) +- Linkedin [http://in.cuban.tech](http://in.cuban.tech) +- Facebook [http://fb.cuban.tech](http://fb.cuban.tech) +- Telegram [http://im.cuban.tech](http://im.cuban.tech) +- Youtube [http://videos.cuban.tech](http://videos.cuban.tech) +- Meetups [http://meetup.cuban.tech](http://meetup.cuban.tech) +- Google+ [http://plus.cuban.tech](http://plus.cuban.tech) +- Slides [http://slides.cuban.tech](http://slides.cuban.tech) +- Control de Versiones [http://git.cuban.tech](http://git.cuban.tech) \ No newline at end of file diff --git a/intro_20180520-es.md b/intro_20180520-es.md new file mode 100644 index 00000000000..b9bb51df008 --- /dev/null +++ b/intro_20180520-es.md @@ -0,0 +1,149 @@ + +## CUBANTECH MEETUP PYDAY, HAVANA 2018 +#### Django workshop + +---------------- + +#### These slides: [slides.cuban.tech/intro_20180729.html](http://slides.cuban.tech/intro_20180729.html) + +------------ + +Author: Olemis Lang (olemis@cuban.tech) + +- Red: cubantech +- Descargas: cubantech_5G +- Password: meet-ups + +------------ + +#### SOCIALIZANDO TECNOLOGÍAS AVANZADAS DE SOFTWARE LIBRE + +[cuban.tech website](http://cuban.tech) + +--- + +## ¿QUÉ ES EL GRUPO CUBANTECH? + +Un grupo de empresarios cubanos con visión social + +![](img/cubantech.map.png) + +-- + +- Socializar el conocimiento a través de actividades educativas +- Enseñanza de la evolución digital en lenguaje natural y lenguaje de programación +- Promover una red sostenible de cooperación y promoción de la innovación tecnológica cubana +- Un complemento para ayudar a las personas comunes que no programan a introducir la tecnología en sus vidas de forma saludable. + +--- + +## REGLAS DE LOS ENCUENTROS + +#### UNA COMUNIDAD LIBRE DE ACOSO PARA TODOS, INDEPENDIENTEMENTE DE: + +- [Código de conducta](https://github.com/nodeschool/havana/blob/master/Code_of_Conduct.md) +- sexo, identidad o expresión de género, orientación sexual, discapacidad, +- apariencia física, edad, tamaño corporal, raza, nacionalidad o creencias religiosas + +-- + + +## REGLAS EXTRAS DEL ANFITRION + +- Preservar el lugar, voz baja, etc. +- Ayúdense a sí mismos con refrescos... fuera de la habitación + +-- + +## OTRAS REGLAS BÁSICAS PARA UNA EXPERIENCIA ATRACTIVA + +- Respeta el límite de tiempo de tu discurso de apertura. +- Pregunte sin importar cuando, pero POR FAVOR PREGUNTE! +- Comparta con los asistentes todo lo que pueda. + +--- + +## Almuerzo + +- 1.75 CUC - Cuarto de pollo asado +- CUC - Chuletas de lomo ahumadas +- $1.75 CUC - Pechugas de pollo asadas + +No proporcionado por nosotros. Ordene temprano para que llegue a tiempo + +--- + +## Encuentros PYDAY + +![](img/python-logo.png) + +#### Agradecimientos! + +- Python Software Foundation + +--- + +## AGENDA DE ESTA REUNION + +- +- +- Depende de ti Alí ... + +--- + +## Recursos + +- Videos [videos.cuban.tech](http://videos.cuban.tech) + - [DjangoCon EU 2018](http://videos.cuban.tech/DjangoCon%20Europe%202018%20in%20%20Heidelberg) + - [PyCon 2017](http://videos.cuban.tech/pycon.2017/) + - [PyCon 2014](http://videos.cuban.tech/pycon.2014/) +- Desarrollado por Docker ... [Descarga instaladores de LAN](ftp://qnap01.local/Public/soft/docker/) + - ... y [docker-compose](ftp://qnap01.local/Public/soft/docker/docker-compose-1.17.1-Linux-x86_64) (renombrar a `docker-compose`) +- [Instrucciones de configuración del entorno](ftp://qnap01.local/Public/meetup/taller_django_20180729/taller/index.html) +- [Django 1.6.12dev documentacion](https://django.readthedocs.io/en/1.6.x/) + [PDF](https://media.readthedocs.org/pdf/django/1.6.x/django.pdf) + - [Réplica Local 1.6.11](http://pkgdocs.cuban.tech/python-django-doc/html/) + [PDF 1.6.x](ftp://qnap01.local/Public/meetup/taller_django_20180729/taller/resources/django-docs-1.6.12dev.pdf) + [PDF 1.11](ftp://qnap01.local/Public/meetup/taller_django_20180729/taller/resources/django-docs-1.11.zip) + - Aviso => Último = `2.2` + +-- + +## PRÓXIMAMENTE + +- Ganadores de predicciones de la Copa Mundial de la FIFA 2018 + +--- + +## PERSONAS INVITADAS + +--- + +## TEMAS PARA LAS PRÓXIMAS REUNIONES + +- 2018/08 - [Contenedores Docker para Skycoin](http://docker.cuban.tech/events/253171588/) +- 2018/10 - [Raspberry Jam La Habana 2018-10](http://meetup.cuban.tech/events/253172694/) + +--- + +### SCIPYLA 2018 + +##### ¡ Nos vamos para Curitiba! - [Talk in CubanTech meetups](http://forms.cuban.tech/cubantech-speak) + +![](img/scipyla2018.annonce.png) + +--- + +## CANALES DE COMUNICACIÓN + +[CUBAN.TECH](http://cuban.tech) SITIO WEB + +- Twitter [http://twitter.cuban.tech](http://twitter.cuban.tech) +- Linkedin [http://in.cuban.tech](http://in.cuban.tech) +- Facebook [http://fb.cuban.tech](http://fb.cuban.tech) +- Telegram [http://im.cuban.tech](http://im.cuban.tech) +- Youtube [http://videos.cuban.tech](http://videos.cuban.tech) +- Meetups [http://meetup.cuban.tech](http://meetup.cuban.tech) +- Google+ [http://plus.cuban.tech](http://plus.cuban.tech) +- Slides [http://slides.cuban.tech](http://slides.cuban.tech) +- Control de Versiones [http://git.cuban.tech](http://git.cuban.tech) \ No newline at end of file diff --git a/intro_20180520.md b/intro_20180520.md index 15e3c6c0420..27f584d4c1f 100644 --- a/intro_20180520.md +++ b/intro_20180520.md @@ -121,7 +121,7 @@ Not provided by us . Order early for it to arrive on time. ## TOPICS FOR NEXT MEETUPS - 2018/08 - [Docker containers for Skycoin](http://docker.cuban.tech/events/253171588/) -- 2018/10 - [Raspberry Jam Havanba 2018-10](http://meetup.cuban.tech/events/253172694/) +- 2018/10 - [Raspberry Jam Havana 2018-10](http://meetup.cuban.tech/events/253172694/) --- diff --git a/intro_20180729-es.md b/intro_20180729-es.md new file mode 100644 index 00000000000..497219faa1f --- /dev/null +++ b/intro_20180729-es.md @@ -0,0 +1,170 @@ + +## CUBANTECH ENCUENTRO PYDAY, HAVANA 2018 +#### Taller de Django, StackOverflow + +---------------- + +#### These slides: [slides.cuban.tech/intro_20180729.html](http://slides.cuban.tech/intro_20180729.html) + +------------ + +Author: Olemis Lang (olemis@cuban.tech) + +Network: cubantech + +Password: meet-ups + +------------ + +#### SOCIALIZANDO TECNOLOGÍAS AVANZADAS DE SOFTWARE LIBRE + +[sitio web cuban.tech](http://cuban.tech) + +--- + +## ¿QUÉ ES EL GRUPO CUBANTECH? + +Un grupo de empresarios cubanos con visión social + +![](img/cubantech.map.png) + +-- + +- Socializar el conocimiento a través de actividades educativas +- Enseñanza de la evolución digital en lenguaje natural y lenguaje de programación +- Promover una red sostenible de cooperación y promoción de la innovación tecnológica cubana +- Un complemento para ayudar a las personas comunes que no programan a introducir la tecnología en sus vidas de forma saludable. + +--- + +## Reglas de los Encuentros + +#### UNA COMUNIDAD LIBRE DE ACOSO PARA TODOS, INDEPENDIENTEMENTE DE: + +- [Código de conducta](https://github.com/nodeschool/havana/blob/master/Code_of_Conduct.md) +- sexo, identidad o expresión de género, orientación sexual, discapacidad, +- apariencia física, edad, tamaño corporal, raza, nacionalidad o creencias religiosas + +-- + +## REGLAS EXTRAS DEL ANFITRION + +- Preservar el lugar, voz baja, etc. +- Ayúdense a sí mismos con refrescos... fuera de la habitación + +-- + +## OTRAS REGLAS BÁSICAS PARA UNA EXPERIENCIA ATRACTIVA + +- Respeta el límite de tiempo de tu discurso de apertura. +- Pregunte sin importar cuando, pero POR FAVOR PREGUNTE! +- Comparta con los asistentes todo lo que pueda. + +--- + + +--- + +## ENCUENTROS PYDAY + +![](img/python-logo.png) + +#### AGRADECIMIENTOS! + +- Python Software Foundation + +--- + +## LE GUSTA NUESTRO LOGO? + +![](img/pythoncuba.logo.png) + +Comentarios y sugerencias via : [http://im.cuban.tech](http://im.cuban.tech) + +--- + +## AGENDA DE ESTA REUNION + +- ¿Qué es una Raspberry Jam? +- Uso del Raspberry Pi como infraestructura para las reuniones +- Charlas +- Propuestas +- Descanso +- Votar +- Laboratorio práctico: HypriotOS - Docker on ARM Boards[slides](docker-stuff/hypriot) +- Más charlas + +--- + +## RECURSOS + +- Videos [media.cuban.tech](http://media.cuban.tech) + - [Adafruit DIY videos](http://videos.cuban.tech/Adafruit.Liked.videos/) +- [Documentación](ftp://qnap01.local/Public/docs/) + - [Revista MagPi](ftp://qnap01.local/Public/docs/magpi) +- Paquetes Raspbian + - [archive.framberrypi.org/](http://archive.raspberrypi.org/) + - [archive.raspbian.org/](http://archive.raspbian.org/) +- Imágenes del SO + - [HypriotOS images](ftp://qnap01.local/Public/os/hypriot) + - Imágenes Raspberry Pi (... algunas subcarpetas en[aquí](ftp://qnap01.local/Public/os/) ) + +-- + +## Mas Recursos + +- Matriz de habilidades CubanTech[forms.cuban.tech/dev-matrix](http://forms.cuban.tech/dev-matrix) + - Ofertas de empleo... ¡te llamaremos! + +-- + +## PRÓXIMAMENTE + +- El reto de los pronósticos de la Liga de Campeones de la UEFA +- El desafío de las predicciones de la Copa Mundial de la FIFA +- El reto de las predicciones de la final de la NBA + +--- + +## PERSONAS INVITADAS +--- + +## TEMAS PARA LAS PRÓXIMAS REUNIONES + +- Python y Julia en Física +- Python en bioinformática +- Economía computacional + +-- + +## TTEMAS PARA LAS PRÓXIMAS REUNIONES + +- Cadena de bloques y DApps impulsados por Python +- Realidad virtual y hardware +- Sistemas de información geográfica +- Python en la ciencia +- Presente su idea de proyecto + +--- + +### SCIPYLA 2018 + +##### ¡ Nos vamos para Curitiba! - [Talk in CubanTech meetups](http://forms.cuban.tech/cubantech-speak) + +![](img/scipyla2018.annonce.png) + +--- + +## CANALES DE COMUNICACIÓN + +[CUBAN.TECH](http://cuban.tech) SITIO WEB + +- Twitter [http://twitter.cuban.tech](http://twitter.cuban.tech) +- Linkedin [http://in.cuban.tech](http://in.cuban.tech) +- Facebook [http://fb.cuban.tech](http://fb.cuban.tech) +- Telegram [http://im.cuban.tech](http://im.cuban.tech) +- Youtube [http://videos.cuban.tech](http://videos.cuban.tech) +- Meetups [http://meetup.cuban.tech](http://meetup.cuban.tech) +- Google+ [http://plus.cuban.tech](http://plus.cuban.tech) +- Slides [http://slides.cuban.tech](http://slides.cuban.tech) +- Control de Versiones [http://git.cuban.tech](http://git.cuban.tech) \ No newline at end of file diff --git a/micropython-es.md b/micropython-es.md new file mode 100644 index 00000000000..2b719ddaf1b --- /dev/null +++ b/micropython-es.md @@ -0,0 +1,2104 @@ +## Introducción a MicroPython + +#### Estas diapositivas: [slides.cuban.tech/micropython.html](http://slides.cuban.tech/micropython.html) + +--- + +### Información Wifi + +Red: cubantech + +Contraseña: meet-ups + +-- + +- Las diapositivas están basadas en una[charla](http://todayispotato.github.io/micropython-talk/#/25) de[Lars de Ridder](https://github.com/todayispotato) +- El taller se basa en gran medida en[Nodebots con el taller CubanTech](http://slides.cuban.tech/nodebots.html) +- ... que se basa en gran medida en un taller de[NY-Javascript](http://www.meetup.com/NY-Javascript) (ver[bit.ly/nyjs-nodebots](http://bit.ly/nyjs-nodebots)) +- ... que se basa en gran medida en un taller de[Francis Gulotta](https://twitter.com/reconbot) y[Rick Waldron](https://twitter.com/rwaldron) +- Puede encontrar las diapositivas para ese taller en[gul.ly/3tjj](http://gul.ly/3tjj) +- Puedes inscribirte en uno de sus talleres en la página[Nodebots NYC Meetup page](http://www.meetup.com/nodebots/) + +--- + +## Las pautas de nuestras comunidad + +[Sé excelente el uno con el otro](https://github.com/nodeschool/havana/blob/master/Code_of_Conduct.md) + +--- + +Próximos Eventos CubanTech + +- [CubanTech meetups](http://meetup.cuban.tech) +- [Encuentros en Cuba](http://docker.cuban.tech) +- [Blockstack Cuba meetups](http://blockstack.cuban.tech) + +--- + +# Un gracias Enorme a nuestro anfitrión + +--- + +## Así que, MicroPython + +¿Quién había oído hablar de él antes? + +¿Y quién lo usó antes? + +¿Por algo serio? + +para algo que está funcionando ahora mismo? + +--- + +## Microcontroladores + Python = MicroPython + +![](img/micropython.png) + +MicroPython es una implementación rápida y sencilla del lenguaje de programación Python (versión 3) que está optimizado para funcionar en un microcontrolador. + +-- + +## En serio...? + +- Puesta en marcha en noviembre de 2013 +- Arranque inicial terminado en abril de 2015 + - £ 97,803 primera campaña + - +£ 200,000 en total +- Código abierto :[github.com/micropython](https://github.com/micropython) + +--- + +## Pero, ¿por qué? + +- Comunidad existente (que te incluye a ti) +- Fácil de aprender, con potentes funciones +- Buena separación entre int y float (a diferencia de JS/Lua) +- Operaciones binarias nativas en 1's y 0's (a diferencia de Lua) +- Ideal para la creación rápida de prototipos +- Puente entre el mundo web y el mundo de la internet de las cosas IoT +- Muchas oportunidades para la optimización! + +-- + +## ...y por qué no CPython? + +Principalmente debido al uso de RAM. Ejemplos: + +- Preasignación de 257 + 5 ints = 4k RAM +- Llamadas a métodos: led.on() crea un objeto de método encuadernado = 20 bytes de RAM + +-- + +## Requisitos teóricos mínimos del sistema + +128kb ROM / 8kb RAM (después de restar otro software) + +##### Puerto UNIX alrededor de 280kb flash + +--- + +# ¿Cómo que Micro? + +-- + +## Principalmente optimizaciones de RAM + +- Muchas cadenas predefinidas en ROM (led, on, read, ...) +- Llamadas a métodos optimizados +- Todo lo que puede estar en ROM, está en ROM +- Recolección de basura: Marcar y barrer (sin conteos de referencia) + +-- + +## Punteros etiquetados + +Un puntero etiquetado es un puntero (concretamente una dirección de memoria) con datos adicionales asociados a él. + +- Entero - xxxx xxxx xxxx xxxx xxx1 +- Cadena - xxxx xxxx xxxx xxxx xx10 +- Objeto - xxxx xxxx xxxx xxxx xx00 + +--- + +# Estado actual de MicroPython + +--- + +## Desarrollo + +- Un desarrollador a tiempo completo, dos colaboradores principales +- Financiado en parte por la Agencia Espacial Europea +- Puesta en marcha en mayo de 2016 para el soporte adecuado de los zócalos ESP8266 +- Parece que está madurando + +--- + +## ¿Está lista la producción? + +Depende de tu placa + +Pero es increíble para la creación de prototipos! + +O para incrustar en juegos y aplicaciones + +-- + +## ¿Incrustar a Python en juegos? + +![](img/civ.iv.jpg) + +... ha ocurrido antes, sin embargo no MicroPython .... + +-- + +### Python embebido para videojuegos + +##### Civilización IV + +![](img/civ.iv.jpg) + +Toda la lógica interna, incluida la IA. La API está disponible. + +-- + +### Python embebido para videojuegos + +##### El templo del mal elemental + +![](img/toee.small.jpg) + +Casi todo excepto el motor de renderizado,[según Steve Moret](http://www.pygame.org/interview/stevemoret.shtml) + +-- + +### Python embebido para videojuegos + +##### El Comandante del Puente de Star Trek + +![](img/BridgeCommander.small.jpg) + +Scripts de las misiones + +-- + +### Python embebido para videojuegos + +##### Crystal Space + +![](img/crystal.space.small.jpg) + +Toda la lógica interna, incluida la IA. La API está disponible. + +-- + +### Python embebido para videojuegos + +##### Battlefield 2 + +![](img/battlefield.4.small.jpeg) + +Juego, resultados, estadísticas del equipo + +--- + +# Algunas tablas apoyadas + +--- + +## El PyBoard + +![](img/pyboard.small.png) + +- Implementación de la referencia +- Inicialmente sólo en la pirámide, ahora en múltiples chips +- ARM 32bit Cortex M4 @ 168Mhz, 1Mb flash, 192kb RAM +- Acelerómetro, RTC, 4 LEDs, 2 interruptores, 30 GPIO + +--- + +## BBC Micro:Bit + +![](img/microbit.small.png) + +16kb RAM, 256kb flash, Cortex M0 @ 16 MHz + +-- + +## BBC Micro:Bit + +Suministrado a _1 millón_ de niños en edad escolar + +- Editor de Python en línea +- Aplicación móvil para cargar código +- Toneladas de documentación, material didáctico, etc. + +-- + +### ...viene con: + +![](img/microbit.pxt.pxt.small.png) + +- Editor gráfico de arrastrar y soltar + +-- + +## BBC Micro: Especificaciones de bits + +- 25 LED +- Dos botones programables +- Acelerómetro y magnetómetro +- Bluetooth +- 5 GPIO + +-- + +## Cómpralo ahora! ... :) + +![](img/microbit.amazon.png) + +El envío es gratuito para pedidos en el Reino Unido \o/ + +--- + +## The WiPy + +![](img/wipy.small.png) + +256kb RAM, 2Mb flash, 25 GPIO, Cortex M4 @ 80 MHz + +#### "Pequeño y ligero para encajar en cualquier cavidad" + +--- + +## LoPy + +![](img/lopy.small.png) + +LoRa + Python + +-- + +## LoRa ... hmmm ? + +[![](img/lora.logo.white.png)](https://www.lora-alliance.org/) + +- Plataforma inalámbrica de largo alcance y bajo consumo +- Elección de la tecnología predominante para la creación de redes de Internet de las cosas(IoT) en todo el mundo. +- +500 miembros +- LoRaWAN Implementación de protocolos + - Especificación WAN de bajo consumo (LPWAN) para dispositivos inalámbricos que funcionan con baterías. + +--- + +## Feather M0 Express + +| | | +| ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- | +| [![](img/feather.m0.express.png)](https://www.adafruit.com/product/3403) |
![](img/adafruit.logo.jpg)
| + +-- + +## Feather M0 con radio + +| | | +| ------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | +| ![](img/feather.m0.lora.png) | ![](img/feather.m0.rfm69hcw.png) | +| RFM59 LoRA - [900 MHz](https://www.adafruit.com/product/3178) | Packet Radio [433 MHz](https://www.adafruit.com/product/3177), [868 or 915 MHz](https://www.adafruit.com/product/3176) | + +-- + +## Feather M0 wireless + +| | | +| -------------------------------------------------------------- | ---------------------------------------------------------- | +| ![](img/feather.m0.atwinc1500.png) | ![](img/feather.m0.bluefruit.png) | +| [WiFi](https://www.adafruit.com/product/3010) | [Bluetooth](https://www.adafruit.com/product/2995) | + +-- + +## Feather M0 Express - especificaciones + +- Memoria USB [cargador de arranque UF2](https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/uf2-bootloader) +- ATSAMD21G18 @ 48MHz con lógica/potencia de 3.3V +- 256 KB de FLASH + 32 KB de RAM +- Cristal de 32.768 KHz para la generación de relojes y RTC +- Regulador de 3.3V con salida de corriente máxima de 500mA +- Soporte nativo para USB (cargador de arranque USB, depuración de puertos serie) + +-- + +## Feather M0 Express - especificaciones + +- 20 pines GPIO (salidas PWM para todos) +- Serial de hardware, I2C, soporte SPI +- 6 entradas analógicas de 12 bits +- 1 x salida analógica de 10 bits (DAC) +- Construido en cargador lipoly 100mA (con LED) +- Pin #13 LED rojo + +--- + +## ESP8266 y NodeMCU + +![](img/feather.huzzah.small.png) + +... también funciona con los chips ESP8266 (es decir, muchos) + +--- + +## NodeMCU v1 pinout + +![](img/nodemcu.v1.pinout.png) + +-- + +## Dispositivo AMICA NodeMCU + +| | | +| ----------------------------- | ------------------------------- | +| ![](img/nodemcu.v1.amica.jpg) | ![](img/nodemcu.v1.amica.2.jpg) | + +--- + +## NodeMCU v2 pinout + +![](img/nodemcu.v2.pinout.png) + +-- + +## NodeMCU devkit - DOIT + +![](img/nodemcu.doit.png) + +-- + +## Dispositivo NodeMCU - Makerfocus D1 mini + +![](img/nodemcu.d1mini.png) + +--- + +## NodeMCU v3 pinout + +![](img/nodemcu.v3.pinout.png) + +-- + +## Geekcreit® LoLin NodeMCU devkit + +![](img/nodemcu.v3.lolin.png) + +--- + +## Adafruit Feather Huzzah ESP8266 + +![](img/feather.huzzah.png) + +-- + +## Feather HUZZAH - Cargador lipoly 100mA + +![](img/feather.huzzah.lipoly.png) + +-- + +## Feather HUZZAH ESP8266 - especificaciones + +- ESP8266 @ 80MHz o 160 MHz +- Lógica/potencia de 3.3V, salida de corriente máxima de 500mA +- 4MB de FLASH (32 MBit) +- CP2104 Convertidor USB-Serial a bordo + - 921600 velocidad de transmisión máxima para la carga +- 9 pines GPIO + - también se puede utilizar como I2C y SPI +- 1 x entradas analógicas 1,0V máx. + +-- + +## Feather HUZZAH ESP8266 -[pinout](https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/pinouts) + +![](img/feather.huzzah.pinout.png) + +--- + +## Adafruit HUZZAH ESP8266 Breakout + +![](img/huzzah.breakout.png) + +-- + +## HUZZAH ESP8266 Breakout - especificaciones + +- 1 x Entrada analógica (1,0 V máx.) +- 9 x GPIO (3.3V lógico) + - También se utiliza para I2C o SPI +- 2 x pines UART +- 2 x 3-6V entradas de alimentación + - Restablecer, habilitar, deshabilitar LDO + - Salida de 3.3V + +-- + +## HUZZAH ESP8266 Breakout - pines de alimentacion + +![](img/huzzah.breakout.pinout.power.png) + +- regulador de voltaje (se pega a 4V a 6V) + - [Diodos Schottky](https://en.wikipedia.org/wiki/Schottky_diode) para tensiones variables +- **VBat** Batería Lipoly +- **V+** : 5V (FTDI/cabecera en serie) + +-- + +## HUZZAH ESP8266 Breakout - pines en serie + +![](img/huzzah.breakout.pinout.serial.png) + +- TX ( 3.3V) y RX ( 5V) + +-- + +## HUZZAH ESP8266 Breakout - Pines GPIO + +![](img/huzzah.breakout.pinout.gpio.png) + +- No hay pull-up en **#0** +- Lógica de 3.3V + - Corriente máxima consumida: 12mA. +- [Hoja de especificaciones completa](http://www.adafruit.com/datasheets/ESP8266_Specifications_English.pdf) + +-- + +## HUZZAH ESP8266 Breakout - otros pines + +![](img/huzzah.breakout.pinout.analog.png) + +- **A** : entrada analógica ( 0 - 1,0V) +- **LDO** : conectar a **GND** para apagar el regulador de 3.3V +- **RST** ( 5V) **EN** ( 3.3V) + - hasta **GND** para reiniciar el ESP8266 + +--- + +## CircuitPython + +| | | +| ------------------------------- | -------------------------- | +| ![](img/circuitpython.logo.png) | ![](img/adafruit.logo.jpg) | + +--- + +## Circuito Playground Express + +![](img/circuitpython.small.png) + +-- + +#### .... viene con + +![](img/makecode.circuitpython.small.png) + +- Editor gráfico de arrastrar y soltar +- Editor en línea de Python y Javascript +- Toneladas de [documentación](http://adafru.it/wpE), material didáctico, etc. + +-- + +### Placa Circuito Playground Express - características + +- ATSAMD21 ARM Procesador Cortex M0 + - 3.3V y 48MHz +- 2 MB de almacenamiento SPI Flash +- Puerto MicroUSB + - Programación y depuración + - Puerto serie + - teclado, ratón + - joystick o MIDI + +-- + +### Placa Circuito Playground Express - otras características + +- 10 x mini NeoPixels +- 1 x sensor de movimiento (LIS3DH) + - Acelerómetro de tres ejes + - Detección de golpes y caídas libres +- 1 x Sensor de temperatura (termistor) +- 1 x Sensor de luz (fototransistor). + - Sensor de color y sensor de pulso. + +-- + +### Placa Circuito Playground Express - más características + +- 1 x micrófono MEMS +- 1 x Mini-altavoz con amplificador clase D +- 2 x Pulsadores +- Receptor y transmisor de infrarrojos + - Recibir y transmitir cualquier código de control remoto + - Enviar mensajes entre Circuitos Playground Expresses + - Sensor de proximidad. + +-- + +### Placa Circuito Playground Express - aún más características + +- 8 x pines de entrada/salida fáciles de pinza de cocodrilo + +![](img/cpx.pinout.png) + +--- + +## Trinket M0 + + ![](img/trinket.m0.small.png) + +Tarjeta programable CircuitPython de bajo costo! + + .... preinstalado nada más sacarlo de la caja! + +-- + +## Trinket M0 - características (vs Trinket) + +- El mismo tamaño, factor de forma y pinout que el Trinket clásico +- ATSAMD21E18 Microcontrolador de 32 bits Cortex M0+ Atmel ATSAMD21 (ATtiny85 8-bit AVR) + - Procesador a 32 bit de 48 MHz (+6x mas rápido) +- 256KB Flash (8KB ⇒ 32x), 32 KB RAM (512B ⇒ 64x) + +-- + +## Trinket M0 - USB + +- USB nativo soportado por todos los sistemas operativos (falta en Trinket) + - Arduino IDE + - Consola serie CircuitPython USB + - Teclado/ratón HID + - .... incluso una pequeña unidad de disco para almacenar scripts Python. + +-- + +## Trinket M0 - otras características + + ![](img/trinket.m0.overview.png) + +- Conector USB Micro B +- 3 LED incorporados (RGB DotStar LED, LED rojo #13, LED ON) +- Botón de reinicio + +-- + +## Trinket M0 - Parte trasera + + ![](img/trinket.m0.small.png) + +- Entrada de batería (unida al pin BAT) para soldar en un conector JST PH y alimentarlo con una batería externa. + - Batería de polímero de litio o paquetes de baterías JST 3xAAA +- Protecciones : polaridad inversa, sobrecorriente y térmica. +- Conmutación entre USB y batería (tensión máxima) + +--- + +## Concluyendo .... + +> Especificaciones de la caja de tu tabla y mantenerlas abiertas. + +-- + +## Adafruit Feather Huzzah ESP8266 + +![](img/feather.huzzah.pinout.png) + +-- + +## Circuito Playground Express + +![](img/cpx.pinout.png) + +-- + +## PyBoard v1.1 + +![](img/pyb.1.1.1.pinout.png) + +-- + +## PyBoard v1.0 + +![](img/pyb.1.0.pinout.png) + +-- + +## PyBoard Lite AC v1.0 + +![](img/pybliteac.1.0.pinout.png) + +-- + +## PyBoard Lite v1.0 + +![](img/pyblite.1.0.pinout.png) + +-- + +## Trinket M0 + +![](img/trinket.m0.pinout.png) + +-- + +## NodeMCU v3 (e.g. LoLin wemos.cc) + +![](img/nodemcu.v3.lolin.pinout.png) + +-- + +## NodeMCU v2 (por ejemplo, DoIT.am) + +![](img/nodemcu.v2.doit.pinout.png) + +-- + +## NodeMCU v1 (por ejemplo, Amica devkit) + +![](img/nodemcu.v1.devkit.pinout.png) + +--- + +## Introducción a PyBoard + +Zero conf + +![](img/pyboard.small.png) + +--- + +## Cómo empezar ESP8266 + +```sh +pip install esptool +``` + +Desde que la Versión 1.3 soporta tanto Python 2.7 como 3.4
(o superior) + +-- + +### Identificar USB - GNU/Linux + +```sh +Monitor de udevadm --udev +imprimirá los eventos recibidos: +UDEV - el evento que udev envía después del procesamiento de reglas + +UDEV [1504678146.578976] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2 (usb) +UDEV [1504678146.746860] add /module/usbserial (module) +UDEV [1504678146.747288] add /bus/usb-serial (bus) +UDEV [1504678146.747855] add /bus/usb/drivers/usbserial (drivers) +UDEV [1504678146.748149] add /bus/usb/drivers/usbserial_generic (drivers) +UDEV [1504678146.748241] add /bus/usb-serial/drivers/generic (drivers) +UDEV [1504678146.772466] add /module/ch341 (module) +UDEV [1504678146.772783] add /bus/usb-serial/drivers/ch341-uart (drivers) +UDEV [1504678146.774556] add /bus/usb/drivers/ch341 (drivers) +UDEV [1504678146.774614] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0 (usb) +UDEV [1504678146.775507] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/ttyUSB0 (usb-serial) +UDEV [1504678146.803046] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/ttyUSB0/tty/ttyUSB0 (tty) +``` + +-- + +### Identificar USB - Mac OS X + +```sh +ls /dev/cu*serial* +/dev/cu.wchusbserial1410 +``` + +-- + +## Borrar y desplegar firmware + +```sh +esptool.py --port /dev/ttyUSB0 borrar_flash +esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect 0 esp8266-20170526-v1.9.bin +``` + +- Especifique el nombre del dispositivo identificado anteriormente después de `--port` +- Reduzca la velocidad de transmisión si se producen errores al parpadear (por ejemplo, hasta 115200). + +-- + +## ...si todavía no funciona... + +Para algunas tarjetas NodeMCU especifique la opción `-fm dio`. + +```sh +esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect -fm dio 0 esp8266-20170526-v1.9.bin +``` + +--- + +## Introducción - cargador de arranque UF2 + +- Descargar archivo de imagen UF2 + - por ejemplo [el último CPX CircuitPython UF2](https://github.com/adafruit/circuitpython/releases/download/2.1.0/adafruit-circuitpython-circuitplayground_express-2.1.0.uf2) para Circuito Playground Express +- Conecte la tarjeta al ordenador mediante un cable de datos USB +- [**OPTIONAL**] Restablece tu tabla. + - Por ejemplo, haga doble clic en el botón Reset situado en el centro del CPX. + +-- + +## Modo de cargador de arranque UF2 + +![](img/circuit_playground_greens.jpg) + +- Comprueba que tu placa está en modo bootloader + - p.ej. todos los LEDs se ponen verdes en el CPX + +-- + +## Unidad de arranque UF2 + +![](img/circuit_playground_cplayboot.gif) + +- Aparece una nueva unidad de disco + - El nombre puede variar, por ejemplo, `CPLAYBOOT` para CPX. + +-- + +## UF2 flasheando + +![](img/circuit_playground_drag.png) + +- Copiar (arrastrar) el archivo de imagen en la unidad de arranque + +--- + +## Cómo empezar - BOSSAC + +- Descargue archivos de imagen BIN, por ejemplo,[último BIN para CPX](https://adafruit-circuit-python.s3.amazonaws.com/index.html?prefix=bin/circuitplayground_express/) +- Descargar [última versión de bossac](https://github.com/shumatech/BOSSA/releases/latest) + - `mingw32` para Windows, `apple-darwin` para Mac OSX, y varias opciones `linux`. + +-- + +## Flash con BOSSAC + +```sh +$ bossac -e -w -v -R ~/Downloads/adafruit-circuitpython-circuitplayground_express-1.0.0.0.bin +``` + +`e` borra el chip, `w` escribe el archivo dado, `v` verifica la escritura y `r` resetea la placa. + +--- + +## REPL sobre el puerto serie + +- Enchufe el cable mini-USB (placa) a USB (portátil) +- Identificar el dispositivo USB +- Conectar a través de una conexión en serie + +-- + +### Identificar y conectar a través de USB - GNU/Linux + + + +```sh +$ udevadm monitor --udev +monitor will print the received events for: +UDEV - the event which udev sends out after rule processing + +UDEV [1504678146.578976] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2 (usb) +UDEV [1504678146.746860] add /module/usbserial (module) +UDEV [1504678146.747288] add /bus/usb-serial (bus) +UDEV [1504678146.747855] add /bus/usb/drivers/usbserial (drivers) +UDEV [1504678146.748149] add /bus/usb/drivers/usbserial_generic (drivers) +UDEV [1504678146.748241] add /bus/usb-serial/drivers/generic (drivers) +UDEV [1504678146.772466] add /module/ch341 (module) +UDEV [1504678146.772783] add /bus/usb-serial/drivers/ch341-uart (drivers) +UDEV [1504678146.774556] add /bus/usb/drivers/ch341 (drivers) +UDEV [1504678146.774614] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0 (usb) +UDEV [1504678146.775507] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/ttyUSB0 (usb-serial) +UDEV [1504678146.803046] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/ttyUSB0/tty/ttyUSB0 (tty) + +$ picocom /dev/ttyUSB0 -b115200 +``` + + + +... no siempre `ttyUSB0` e.g. `ttyACM0`. + +-- + +### Identificar y conectar a través de USB - Mac OS X + +```sh +$ ls /dev/cu*serial* +/dev/cu.wchusbserial1410 + +$ screen /dev/cu.wchusbserial1410 115200 -L +MicroPython v1.9-8-gfcaadf92 on 2017-05-26; ESP module with ESP8266 +Type "help()" for more information. +>>> +``` + +... El nombre del dispositivo puede no ser `/dev/cu.wchusbserial1410`. + +-- + +### Conectar a través de USB - Windows PuTTY + +![](img/putty.config.serial.png) + +.... ajustar la velocidad a `115200` (en lugar de `9600`) + +-- + +### Conectar a través de USB - Windows TeraTerm + +![](img/teraterm.config.serial.png) + +--- + +# Perdona... + +# ¿Qué es MicroPython? + +--- + +## ¡Es Python! (3.4-ish) + +```python +>>> print('Hola mundo!') +Hola mundo! + +>>> with open('cubantech.txt', 'w') as f: +>>> f.write('Hola CubanTech!') + +>>> with open('cubantech.txt', 'r') as f: +>>> for l in f: +>>> print l +Hola CubanTech! + +>>> try: +>>> 1/0 +>>> except ZeroDivisionError as e: +>>> print("Oh, you!") +Oh, you! +``` + +--- + +## ...pero no todo. + +```python +>>> import functools +Traceback (most recent call last): + File "", line 1, in +ImportError: no module named 'functools' +>>> import this +Traceback (most recent call last): + File "", line 1, in +ImportError: no module named 'this' +``` + +--- + +## Módulos soportados + +- `sys` +- `time` +- `struct` +- `machine` - Funciones de la máquina relacionadas con la placa +- `micropython` - internos +- Los puertos específicos proporcionan ganchos específicos, REPL y módulos personalizados + +--- + +## Biblioteca estándar externa + +Escrito en Python (¿recuerdas PyPy?) + +```sh +$ micropython -m upip install micropython-functools +$ ./micropython +MicroPython v1.7-116-g8dd704b on 2016-04-19; linux version +Use Ctrl-D to exit, Ctrl-E for paste mode +>>> import functools +>>> dir(functools) +['__name__', 'reduce', 'partial', 'update_wrapper', '__file__', 'wraps'] +https://github.com/micropython/micropython-lib +``` + +--- + +## Soporta sintaxis asíncrona/en espera + +```python +async def ping_pygrunn(): + return await ping_server('pygrunn.org') +``` + +--- + +# APIs de hardware + + .... para PyBoard y chips STM + +-- + +## Sus micro-superpoderes incluyen: + +- Desactivar interrupciones +- Activar y desactivar GC +- Escribir ensamblador en línea +- Emitir código de byte o código máquina + +-- + +## Ensamblador en línea - Devolver un valor + +```python +>>> @micropython.asm_thumb +... def fun(): +... movw(r0, 42) +... +>>> print(fun()) +``` + +¿Cuál es el resultado? + +-- + +## Ensamblador en línea - periféricos + +```python +@micropython.asm_thumb +def led_on(): + movwt(r0, stm.GPIOA) + movw(r1, 1 << 13) + strh(r1, [r0, stm.GPIO_BSRRL]) +``` + +Encienda el LED rojo del PyBoard (es decir, PA13 high) + +> - `stm` - Constantes de PyBoard +> - `stm.GPIOA` - desplazamiento de dirección de memoria a GPIOA +> - `movwt` mueve un 32-bit al registro (`movw` + `movt`) +> - `GPIO_BSRRL` - STM32 Bit Registro de Cambio/reinicio + +-- + +## Ensamblador en línea - Argumentos + +```python + +>>> @micropython.asm_thumb +... def asm_add(r0, r1): +... add(r0, r0, r1) +... +>>> asm_add(1, 2) +3 +``` + +- Hasta 4 argumentos +- Deben llamarse `r0`, `r1`, `r2` y `r3`. + +-- + +## Ensamblador en línea - Flash LED r0 veces + +```python + +@micropython.asm_thumb +def flash_led(r0): + # get the GPIOA address in r1 + movwt(r1, stm.GPIOA) + + # get the bit mask for PA14 (the pin LED #2 is on) + movw(r2, 1 << 14) + b(loop_entry) + label(loop1) + + # turn LED on + strh(r2, [r1, stm.GPIO_BSRRL]) + + # delay for a bit + movwt(r4, 5599900) + label(delay_on) + sub(r4, r4, 1) + cmp(r4, 0) + bgt(delay_on) + + # turn LED off + strh(r2, [r1, stm.GPIO_BSRRH]) + + # delay for a bit + movwt(r4, 5599900) + label(delay_off) + sub(r4, r4, 1) + cmp(r4, 0) + bgt(delay_off) + + # loop r0 times + sub(r0, r0, 1) + label(loop_entry) + cmp(r0, 0) + bgt(loop1) +``` + +- `label(x)` - asignar etiqueta +- `b(x)` rama incondicional +- `bgt(x)`, `blt(x)`, ... rama condicional + +-- + +## Emisor de código nativo + +```python + +@micropython.native +def foo(self, arg): + # code +``` + +Aproximadamente el doble de rápido, pero más grande binario + +-- + +## Viper es Python incrustada en tiempo real + +```python + +@micropython.viper +def foo(self, arg: int) -> int: + # code +``` + +- Ahora en realidad llamado Zerynth y algo confuso +- No totalmente conforme con las normas de Código Python +- Produce instrucciones para la máquina + +--- + +# Vamos entonces! + +--- + +## Nuestro hardware + +[![](img/ardx-hardware-kit-closed.jpg)](http://www.seeedstudio.com/depot/ARDX-The-starter-kit-for-Arduino-p-1153.html) + +-- + +## Nuestro hardware + +[![](img/ardx-hardware-kit-open.jpg)](http://www.seeedstudio.com/depot/ARDX-The-starter-kit-for-Arduino-p-1153.html) + +--- + +## A los kits les puede faltar equipo + +--- + +Si tiene problemas para encontrar un componente, háganoslo saber y le conseguiremos un reemplazo. + +--- + +## ¿No funciona? + +## ¡Probablemente hardware! + +--- + +Siéntase libre de seleccionar los componentes que más le gusten y completar los retos que más le interesen. + +--- + +## Componentes que estamos cubriendo + +- Programación en red con ESP8266 +- LEDs (diodos emisores de luz) +- Botones +- Servos +- Aplicaciones de internet de las cosas IOT con MQTTT + +--- + +## Redes (MicroPython en ESP8266) + +- Punto de acceso WiFi (AP) + - ESSID es de la forma MicroPython-xxxxxxxx (dirección MAC de su dispositivo) + - Restablecimiento de fábrica Contraseña `micropythoN` + - Dirección IP `192.168.4.1` +- Interfaz de la estación + +--- + +## Módulo de red + +```python +>>> import network +>>> sta_if = network.WLAN(network.STA_IF) +>>> ap_if = network.WLAN(network.AP_IF) + +``` + +--- + +## Estado de activación de la interfaz (red) + +```python +>>> sta_if.active() +False +>>> ap_if.active() +True +>>> ap_if.config('essid') +MicroPython-04320781 +>>> ap_if.config(essid='micropy012') +>>> ap_if.ifconfig() +('192.168.4.1', '255.255.255.0', '192.168.4.1', '8.8.8.8') +``` + +Los valores devueltos son: Dirección IP, máscara de red, pasarela, DNS. + +-- + +## Configuración de red - Parámetros + +| Parámetro | Tipo | Descripción | +| ---------- | ------ | ---------------------------------------------------- | +| _mac_ | bytes | Dirección MAC (bytes) | +| _essid_ | string | Nombre del punto de acceso WiFi (cadena) | +| _channel_ | int | Canal WiFi (entero) | +| _hidden_ | bool | Si el ESSID está oculto | +| _authmode_ | enum | Modo de autenticación soportado (ver `dir(network)`) | +| _password_ | string | Contraseña de acceso WiFi | + +--- + +## Configuración de red + +```python +>>> sta_if.active(True) +>>> sta_if.connect('cubantech', 'meet-ups') +>>> sta_if.isconnected() # Podria llevar un tiempo +True +>>> sta_if.ifconfig() +('192.168.0.2', '255.255.255.0', '192.168.0.1', '8.8.8.8') + +``` + +--- + +## Instala WebREPL si aún no lo has hecho + +##### ...de Internet. + +```sh +git clone https://github.com/micropython/webrepl +``` + +[Descargar WebREPL de Internet](https://github.com/micropython/webrepl) + +##### ...de CubanTech LAN + +```sh +git clone ssh://git@git.cuban.tech:2222/micropython/webrepl.git +``` + +[Descargar WebREPL desde LAN](http://git.cuban.tech/micropython/webrepl/repository/archive.tar.gz?ref=master) + +--- + +## Configurar el acceso a WebREPL (a través de USB) + +```python +import webrepl_setup +``` + +- Siga las instrucciones y avisos en pantalla +- Reinicie su dispositivo MicroPython. + +--- + +## WebREPL + +![](img/webrepl.png) + +- Conectar al punto de acceso del ESP8266 +- Lanzar WebREPL + - Abra `webrepl.html` en su navegador +- Haga clic en el botón "Conectar +- Escribe la contraseña con `webrepl_setup` cuando se te pida + +--- + +## Tenemos WiFi + +```python +>>> import socket +``` + +¡¡¡Tenemos sockets!!!! + +--- + +## Servidor HTTP simple + +Estado de todos los pines GPIO + +```python +import machine +pins = [machine.Pin(i, machine.Pin.IN) for i in (0, 2, 4, 5, 12, 13, 14, 15)] +html = """ + + ESP8266 Pins + +

ESP8266 Pins

+ %s
PinValue
+ + +""" + +import socket +addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] +s = socket.socket() +s.bind(addr) +s.listen(1) +print('listening on', addr) +while True: + cl, addr = s.accept() + print('client connected from', addr) cl_file = cl.makefile('rwb', 0) + while True: + line = cl_file.readline() + if not line or line == b'\r\n': + break + rows = ['%s%d' % (str(p), p.value()) for p in pins] response = html % '\n'.join(rows) + cl.send(response) + cl.close() +``` + +--- + +## Componentes que estamos cubriendo + +- Programación en red con ESP8266 +- LEDs (diodos emisores de luz) +- Botones +- Servos +- Aplicaciones de Internet de las cosas (IoT) con MQTTT + +--- + +## LEDs + +#### Luz Emitiendo Diodos + +![](img/leds.jpg) + +--- + +## Pines de identificación de LEDs + +- El pin largo es positivo (y se pone en marcha) +- El pin corto es negativo (y va a tierra) + +![](img/led-pin-diagram.png) + +--- + +## Breadboards: Cableado sin soldadura + +#### Los Breadboards nos permiten cablear rápidamente los componentes para hacer prototipos + +![](img/breadboard.small.png) + +--- + +## Breadboards: Conexiones eléctricas + +- #### Aquí puedes ver cómo se conectan las diferentes filas y columnas. +- #### Si no está claro, no dudes en buscar en Google o pedirle a un voluntario que te lo explique. + +![](img/breadboard-diagram.small.jpg) + +## Usa tu breadboard y un par de cables (el color no importa) para construir esto + +![](img/arduino-led-breadboard.png) + +--- + +## Construye esto - Feather HUZZAH ESP8266 + +![](img/feather.huzzah.led.png) + +-- + +## Alternativa - PyBoard + +![](img/pyboard.led.png) + +-- + +## Alternativa - NodeMCU v3 + +![](img/nodemcu.v3.led.png) + +--- + +Ejecutar esta en (USB o web) REPL + +```python +import machine +import time + +pin_id = 4 # NodeMCU + # PyBoard = 'A14' + # Huzzah Feather = 15 +led = machine.Pin(pin_id, machine.Pin.OUT) +while True: + led.high() + time.sleep(0.5) + led.low() + time.sleep(0.5) +``` + +salida del Bucle con `Ctrl-c` + +-- + +## LEDs incorporados (PyBoard) + +| Nombre físico | Nombre de la CPU | Descripción del LED | +| ------------- | ---------------- | ------------------- | +| P2 | B4 | LED azul | +| P3 | A15 | LED amarillo | +| P4 | A14 | LED verde | +| P5 | A13 | LED rojo | + +-- + +## LEDs incorporados (Huzzah) + +- LED rojo en el pin 0 +- LED azul en el pin 2 + +--- + +## Si tiene éxito, deberías ver esto + +![](img/huzzah.blinking-led.gif) + +--- + +## Cambio de la frecuencia de parpadeo + +- Probablemente notó que la luz parpadea cada 0,5 segundos. +- Cambie el código para que parpadee a una velocidad diferente y luego vuelva a ejecutarlo para asegurarse de que funciona. +- Si está atascado, presione ↓ para ver una solución potencial + +-- + +```python +import machine +import time + +pin_id = 4 # NodeMCU + # PyBoard = 'A14' + # Huzzah Feather = 15 +led = machine.Pin(pin_id, machine.Pin.OUT) +while True: + led.high() + time.sleep(3.0) + led.low() + time.sleep(3.0) +``` + +--- + +## Desafíos del LED + +Ahora que tiene los fundamentos de los LEDs, puede pasar al siguiente componente o trabajar en algunos desafíos de los LEDs. + +- Pulse → para pasar al siguiente componente +- Pulse ↓ para desplazarse por los desafíos de los LEDs + +-- + +## Desafíos del LED + +_¡Intenta resolverlos tú mismo antes de mirar la solución!_ + +Pulse ↓ para desplazarse por los siguientes retos (y posibles soluciones) + +1. Múltiples luces +2. Luces navideñas +3. Contador binario + +-- + +### 1. Múltiples luces + +Haga que 2 (o más) luces se alternen parpadeando + +![](img/alternate-blinking.gif) + +-- + +### Solución Potencial de Múltiples Luces - Hardware + +![](img/alternate-blinking-hardware.png) + +-- + +### Solución Potencial de Múltiples Luces - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led1 = new five.Led(10); + var led2 = new five.Led(11); + var flag = false; + + setInterval(function() { + if (flag) { + led1.on(); + led2.off(); + } else { + led1.off(); + led2.on(); + } + + flag = !flag; + }, 500); +}); +``` + +-- + +### 2. Luces navideñas + +#### Haz que un LED (o varios LEDs) pasen por diferentes configuraciones, como hacen algunas luces navideñas. Debería cambiar el ajuste cada pocos segundos. A continuación se muestran algunos ejemplos de configuración. Puede ver un ejemplo en la siguiente diapositiva. + +- Apagado +- Sólido +- Parpadeando +- Pulsos (desvanecimiento hacia adentro y hacia afuera) +- Diferentes velocidades de parpadeo, pulsación o alternancia +- Alternando qué luces están encendidas + +-- + +### 2. Luces navideñas + +![](img/holiday-lights.gif) + +-- + +### Potencial solución de luces navideñas - Hardware + +![](img/holiday-lights-hardware.gif) + +-- + +### Potencial solución para las luces navideñas - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + var setting = 0; + + setInterval(function() { + led.stop(); // If we call pulse, we need to stop it + switch (setting) { + case 0: + led.pulse(); + break; + case 1: + led.off(); + break; + case 2: + led.on(); + break; + } + setting = (setting + 1) % 3; + }, 3000); +}); +``` + +-- + +### 2. Luces navideñas (bonos) + +1. Exponer una función a la REPL que le permite cambiar a la siguiente configuración desde la REPL +2. Añada un botón que, al pulsarlo, pase a la siguiente configuración (Nota: debe completar las diapositivas del componente de botones antes de intentarlo). + +-- + +### Potencial solución de Bonus 1 para luces navideñas - Hardware + +![](img/holiday-lights-hardware.gif) + +-- + +### Posible solución de bonificación por luces navideñas 1 - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + var setting = 0; + + function changeSetting() { + led.stop(); // Si llamamos al pulso, tenemos que detenerlo + switch (setting) { + case 0: + led.pulse(); + break; + case 1: + led.off(); + break; + case 2: + led.on(); + break; + } + setting = (setting + 1) % 3; + } + + this.repl.inject({ + cs: changeSetting // Ahora podemos llamar a cs() desde el REPL + }); +}); +``` + +-- + +### Potencial solución para luces navideñas Bonus 2 + +¡Estás por tu cuenta en esto! + +-- + +### 3. Contador binario + +Usando 3 LEDs, cuente de 0 a 7 en binario como se muestra a continuación. Encendido(On) representa 1 y Apagado(off) repesentes 0. + +![](img/binary-counter.gif) + +-- + +### Solución de contador binario potencial - Hardware + +![](img/binary-counter-hardware.png) + +-- + +### Solución de contador binaria potencial (alt 1) - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led1 = new five.Led(9); + var led2 = new five.Led(10); + var led3 = new five.Led(11); + var num = 0; + + setInterval(function() { + var binary = num.toString(2); + + binary.slice(-1) === "1" ? led1.on() : led1.off(); + binary.slice(-2, -1) === "1" ? led2.on() : led2.off(); + binary.slice(-3, -2) === "1" ? led3.on() : led3.off(); + + num = (num + 1) % 8; + }, 1000); +}); +``` + +-- + +### Solución de contador binaria potencial (alt 2) - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var leds = [new five.Led(9), new five.Led(10), new five.Led(11)]; + var num = 0; + + setInterval(function() { + var mask = 1; + + for (var i = 0; i < leds.length; ++i, mask <<= 1) { + var led = led[i]; + num & mask ? led.on() : led.off(); + } + + num = (num + 1) % 8; + }, 1000); +}); +``` + +-- + +### 3. Contador binario (Bono) + +Permite al usuario introducir un número a través de la REPL y mostrarlo en binario en los LEDs. + +-- + +### Solución potencial de bono de contador binario + +¡Estás por tu cuenta en esto! + +--- + +## Componentes que estamos cubriendo + +- Programación en red con ESP8266 +- LEDs (diodos emisores de luz) +- Botones +- Servos +- Aplicaciones de IO con MQTTT + +--- + +## Botones + +![](img/buttons.jpg) + +--- + +## Construye Esto + +![](img/button-hardware.png) + +--- + +## Guarda esto en un archivo y ejecútalo + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var button = new five.Button(2); + + button.on("press", function() { + console.log("Button Pressed!"); + }); + + button.on("hold", function() { + console.log("Button Held!"); + }); + + button.on("release", function() { + console.log("Button Released!"); + }); +}); +``` + +`node button.js` + +--- + +Intente presionar, soltar y mantener presionado el botón + +Debería ver alguna salida como esta en el REPL + +``` + +>> Botón pulsado! +Botón liberado! +Botón pulsado! +Botón liberado! +Botón pulsado! +Botón retenido! +Botón retenido! +Botón liberado! +``` + +--- + +## ¡Añadamos un LED! + +![](img/button-led-hardware.png) + +--- + +## Guarda esto en un archivo y ejecútalo + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + var button = new five.Button(2); + + button.on("press", function() { + led.on(); + }); + + button.on("hold", function() { + led.blink(50); + }); + + button.on("release", function() { + led.stop().off(); + }); +}); +``` + +`node button_led.js` + +--- + +El LED debe encenderse al presionar, apagarse al soltarlo y parpadear al mantenerlo presionado. + +--- + +## Desafíos de los botones + +Ahora que tiene los conceptos básicos de los botones, puede pasar al siguiente componente o trabajar en algunos desafíos de botones. + +- Pulse → para pasar al siguiente componente +- Presione ↓ para desplazarse por los desafíos del botón + +-- + +## Desafíos de los botones + +_¡Intenta resolverlos tú mismo antes de mirar la solución!_ + +Pulse ↓ para desplazarse por los siguientes retos (y posibles soluciones) + +1. Interruptor de luz +2. Clave de acceso +3. Luces navideñas + +-- + +### 1. Interruptor de luz + +Haga que al presionar un botón alternativamente encienda y apague un LED + +-- + +### Solución de interruptor de luz potencial - Hardware + +![](img/light-switch-hardware.png) + +-- + +### Solución de interruptor de luz potencial - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + var button = new five.Button(2); + var on = false; + + button.on("press", function() { + if (on) { + led.off(); + } else { + led.on(); + } + + on = !on; + }); +}); +``` + +-- + +### 2. Clave de acceso + +Dispone de 2 botones y 1 LED. Hágalo de manera que tenga que presionar los botones en cierto orden para encender el LED. + +-- + +### Posible solución de código de acceso - Hardware + +![](img/passcode-hardware.png) + +-- + +### Posible solución de código de acceso - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + var button1 = new five.Button(2); + var button2 = new five.Button(4); + + var passcode = "12112"; + var presses = ""; + + button1.on("press", function() { + presses += "1"; + if (presses.indexOf(passcode) > -1) { + led.on(); + } + }); + + button2.on("press", function() { + presses += "2"; + if (presses.indexOf(passcode) > -1) { + led.on(); + } + }); +}); +``` + +-- + +### 3. Luces navideñas + +#### Haz que un LED (o varios LEDs) pasen por diferentes configuraciones, como hacen algunas luces navideñas. Debe cambiar el ajuste cada vez que se pulsa el botón. A continuación se muestran algunos ejemplos de configuración. + +- Apagado +- Sólido +- Parpadeando +- Pulsos (desvanecimiento hacia adentro y hacia afuera) +- Diferentes velocidades de parpadeo, pulsación o alternancia +- Alternando qué luces están encendidas + +-- + +### Potencial solución para las luces navideñas + +¡Estás por tu cuenta en esto! + +--- + +## Componentes que estamos cubriendo + +- Programación en red con ESP8266 +- LEDs (diodos emisores de luz) +- Botones +- Servos + +--- + +## SERVOS + +![](img/servo.jpg) + +--- + +Toma tu servo y añádele uno de los adjuntos. + +![](img/servo.jpg) + +--- + +## Construye esto + +![](img/servo-hardware.png) + +--- + +## Guarda esto en un archivo y ejecútalo + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var servo = new five.Servo(11); + + this.repl.inject({ + servo: servo + }); +}); +``` + +`node servo.js` + +--- + +Escribe estos comandos en la REPL y observa cómo reacciona el servo + +```js +> servo.to(10); // muevete a 10 grados + +> servo.to(200); // muevete a 200 grados + +> servo.value; // Obtener posición actual + +> servo.min(); + +> servo.max(); + +> servo.range; + +> servo.center(); + +> servo.sweep(); +``` + +--- + +## Servo Challenges + +Ahora que tienes los fundamentos de los servos, puedes pasar al siguiente componente o trabajar en algunos desafíos de los servos. + +Pulse → para pasar al siguiente componente +Pulse ↓ para desplazarse por los desafíos de los servos + +-- + +## Servo Challenges + +_¡Intenta resolverlos tú mismo antes de mirar la solución!_ + +Pulse ↓ para desplazarse por los siguientes retos (y posibles soluciones) + +1. Rociador +2. Flechas +3. Botón + +-- + +### 1. Rociador + +Haz que el servo gire de un lado a otro como si fuera un aspersor. + +![](img/sprinkler.gif) + +-- + +### Solución potencial de rociadores - Hardware + +![](img/sprinkler-hardware.png) + +-- + +### Solución potencial de rociadores - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var servo = new five.Servo(11); + var min = servo.range[0]; + var max = servo.range[1]; + var value = min; + + function step() { + servo.to(value); + value = (value + 45) % max; + setTimeout(step, 500); + } + + step(); +}); +``` + +-- + +### 2. Flechas + +Haz que al presionar el botón de flecha izquierda gire el servo en una dirección y al presionar el botón de flecha derecha gire en la otra dirección. + +![](img/servo-arrows.gif) + +-- + +### Solución de Flechas Potenciales - Hardware + +![](img/servo-arrows-hardware.png) + +-- + +### Solución de flechas potenciales - Código + +```js +var five = require("johnny-five"); +var keypress = require("keypress"); +var board = new five.Board(); + +board.on("ready", function() { + var servo = new five.Servo(11); + + process.stdin.on("keypress", function(ch, key) { + if (key && key.name === "left") { + servo.min(); + } else if (key && key.name === "right") { + servo.max(); + } + }); + + process.stdin.setRawMode(true); + process.stdin.resume(); +}); +``` + +-- + +### 3. Botón + +Haz que el servo barra mientras se mantiene pulsado un botón + +![](img/servo-sweep.gif) + +-- + +### Potencial Solución de Botón - Hardware + +![](img/servo-sweep-hardware.png) + +-- + +### Potencial Solución de Botón - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var servo = new five.Servo(11); + var button = new five.Button(2); + + button.on("press", function() { + servo.sweep(); + }); + + button.on("release", function() { + servo.stop(); + }); +}); +``` + +--- + +Uh oh oh! Nos quedamos sin Diapositivas! Siéntase libre de probar algunos de los otros componentes de su kit mientras nosotros añadimos más! + +--- + +## Liquidacion + +- Gracias por venir! +- Nos encantaría conocer su opinión: [bit.ly/cubantech-nodebots-feedback](http://bit.ly/nodebots-feedback) +- Por favor, guarde los kits (puede comprar los suyos propios[aquí](http://www.seeedstudio.com/depot/ARDX-The-starter-kit-for-Arduino-p-1153.html)) diff --git a/micropython.md b/micropython.md index 4258ccbc8a1..987d771b13b 100644 --- a/micropython.md +++ b/micropython.md @@ -1,10 +1,8 @@ - - ## Introduction to MicroPython #### These slides: [slides.cuban.tech/micropython.html](http://slides.cuban.tech/micropython.html) ----------------- +--- ### Wifi Info @@ -65,8 +63,8 @@ MicroPython is a lean and fast implementation of the Python (version 3) programm - Kickstarted in November 2013 - Original kickstarter ended April 2015 - * £97,803 first campaign - * +£200,000 in total + - £97,803 first campaign + - +£200,000 in total - Code open source : [github.com/micropython](https://github.com/micropython) --- @@ -229,7 +227,7 @@ Gameplay , scores , team stats ## BBC Micro:Bit -Supplied to *1 million* school children +Supplied to _1 million_ school children - Online Python editor - Mobile app to upload code @@ -285,38 +283,36 @@ LoRa + Python [![](img/lora.logo.white.png)](https://www.lora-alliance.org/) -- Long range, low power wireless platform +- Long range, low power wireless platform - Prevailing technology choice for building IoT networks worldwide. - +500 members - LoRaWAN Protocol Deployments - * Low Power WAN (LPWAN) specification for wireless battery operated Things + - Low Power WAN (LPWAN) specification for wireless battery operated Things --- ## Feather M0 Express -| | | -|-----------------------------|------------------------| +| | | +| ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- | | [![](img/feather.m0.express.png)](https://www.adafruit.com/product/3403) |
![](img/adafruit.logo.jpg)
| - - -- ## Feather M0 with radio -| | | -|------------------------------------|-----------------------------------------------------------------------| -| ![](img/feather.m0.lora.png) | ![](img/feather.m0.rfm69hcw.png) | +| | | +| ------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | +| ![](img/feather.m0.lora.png) | ![](img/feather.m0.rfm69hcw.png) | | RFM59 LoRA - [900 MHz](https://www.adafruit.com/product/3178) | Packet Radio [433 MHz](https://www.adafruit.com/product/3177), [868 or 915 MHz](https://www.adafruit.com/product/3176) | -- ## Feather M0 wireless -| | | -|------------------------------------|-----------------------------------------------------------------------| -| ![](img/feather.m0.atwinc1500.png) | ![](img/feather.m0.bluefruit.png) | +| | | +| -------------------------------------------------------------- | ---------------------------------------------------------- | +| ![](img/feather.m0.atwinc1500.png) | ![](img/feather.m0.bluefruit.png) | | [WiFi](https://www.adafruit.com/product/3010) | [Bluetooth](https://www.adafruit.com/product/2995) | -- @@ -347,7 +343,7 @@ LoRa + Python ![](img/feather.huzzah.small.png) -... also runs on ESP8266 (i.e. a lot of) chips +... also runs on ESP8266 (i.e. a lot of) chips --- @@ -359,8 +355,8 @@ LoRa + Python ## AMICA NodeMCU devkit -| | | -|-------------------------------|-------------------------------| +| | | +| ----------------------------- | ------------------------------- | | ![](img/nodemcu.v1.amica.jpg) | ![](img/nodemcu.v1.amica.2.jpg) | --- @@ -409,13 +405,13 @@ LoRa + Python ## Feather HUZZAH ESP8266 - specs -- ESP8266 @ 80MHz or 160 MHz +- ESP8266 @ 80MHz or 160 MHz - 3.3V logic/power, 500mA peak current output - 4MB of FLASH (32 MBit) - CP2104 USB-Serial converter onboard - * 921600 max baudrate for uploading + - 921600 max baudrate for uploading - 9 GPIO pins - * can also be used as I2C and SPI + - can also be used as I2C and SPI - 1 x analog inputs 1.0V max -- @@ -436,11 +432,11 @@ LoRa + Python - 1 x Analog input (1.0V max) - 9 x GPIO (3.3V logic) - * Also used for I2C or SPI + - Also used for I2C or SPI - 2 x UART pins - 2 x 3-6V power inputs - * reset, enable, LDO-disable - * 3.3V output + - reset, enable, LDO-disable + - 3.3V output -- @@ -449,7 +445,7 @@ LoRa + Python ![](img/huzzah.breakout.pinout.power.png) - voltage regulator (stick to 4V to 6V) - * [Schottky diodes](https://en.wikipedia.org/wiki/Schottky_diode) for variable voltages + - [Schottky diodes](https://en.wikipedia.org/wiki/Schottky_diode) for variable voltages - **VBat** : Lipoly battery - **V+** : 5V ( FTDI/serial header ) @@ -468,8 +464,8 @@ LoRa + Python ![](img/huzzah.breakout.pinout.gpio.png) - No pull-up in **#0** -- 3.3V logic - * max current drawn : 12mA. +- 3.3V logic + - max current drawn : 12mA. - [Full spec sheet](http://www.adafruit.com/datasheets/ESP8266_Specifications_English.pdf) -- @@ -481,14 +477,14 @@ LoRa + Python - **A** : analog input ( 0 - 1.0V ) - **LDO** : connect to **GND** to turn 3.3V regulator off - **RST** ( 5V ) **EN** ( 3.3V ) - * down to **GND** to reset ESP8266 + - down to **GND** to reset ESP8266 --- ## CircuitPython -| | | -|-----------------------------|------------------------| +| | | +| ------------------------------- | -------------------------- | | ![](img/circuitpython.logo.png) | ![](img/adafruit.logo.jpg) | --- @@ -512,13 +508,13 @@ LoRa + Python ### Circuit Playground Express board - features - ATSAMD21 ARM Cortex M0 Processor - * 3.3V and 48MHz + - 3.3V and 48MHz - 2 MB of SPI Flash storage - MicroUSB port - * Programming and debugging - * serial port - * keyboard, mouse - * joystick or MIDI + - Programming and debugging + - serial port + - keyboard, mouse + - joystick or MIDI -- @@ -526,11 +522,11 @@ LoRa + Python - 10 x mini NeoPixels - 1 x Motion sensor (LIS3DH) - * Triple-axis accelerometer - * Tap and free-fall detection + - Triple-axis accelerometer + - Tap and free-fall detection - 1 x Temperature sensor (thermistor) - 1 x Light sensor (phototransistor). - * Color sensor and pulse sensor. + - Color sensor and pulse sensor. -- @@ -540,9 +536,9 @@ LoRa + Python - 1 x Mini speaker with class D amplifier - 2 x Push buttons - Infrared receiver and transmitter - * Receive and transmit any remote control codes - * Send messages between Circuit Playground Expresses - * Proximity sensor. + - Receive and transmit any remote control codes + - Send messages between Circuit Playground Expresses + - Proximity sensor. -- @@ -568,7 +564,7 @@ Lowest-cost CircuitPython programmable board! - Same size, form-factor, and pinout as classic Trinket - ATSAMD21E18 32-bit Cortex M0+ Atmel ATSAMD21 microcontroller (ATtiny85 8-bit AVR) - * 48 MHz 32 bit processor (+6x faster) + - 48 MHz 32 bit processor (+6x faster) - 256KB Flash (8KB ⇒ 32x), 32 KB RAM (512B ⇒ 64x) -- @@ -576,10 +572,10 @@ Lowest-cost CircuitPython programmable board! ## Trinket M0 - USB - Native USB supported by every OS (missing in Trinket) - * Arduino IDE - * CircuitPython USB serial console - * Keyboard/Mouse HID - * ... even a little disk drive for storing Python scripts. + - Arduino IDE + - CircuitPython USB serial console + - Keyboard/Mouse HID + - ... even a little disk drive for storing Python scripts. -- @@ -598,7 +594,7 @@ Lowest-cost CircuitPython programmable board! ![](img/trinket.m0.small.png) - Battery Input (tied to the BAT pin) to solder on a JST PH connector to power it from an external battery. - * Lithium Polymer battery or JST 3xAAA battery packs + - Lithium Polymer battery or JST 3xAAA battery packs - Protections : reverse-polarity, over-current and thermal. - Switch between USB and battery (highest voltage) @@ -606,7 +602,7 @@ Lowest-cost CircuitPython programmable board! ## Wrapping up ... -> Checkout specs of your board ↓ ... and keep them open +> Checkout specs of your board ↓ ... and keep them open -- @@ -660,7 +656,7 @@ Lowest-cost CircuitPython programmable board! ## NodeMCU v2 (e.g. DoIT.am) -
![](img/nodemcu.v2.doit.pinout.png)
+![](img/nodemcu.v2.doit.pinout.png) -- @@ -750,10 +746,10 @@ esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect -fm ## Getting started - UF2 bootloader - Download UF2 image file - * e.g. [the latest CPX CircuitPython UF2](https://github.com/adafruit/circuitpython/releases/download/2.1.0/adafruit-circuitpython-circuitplayground_express-2.1.0.uf2) for Circuit Playground Express + - e.g. [the latest CPX CircuitPython UF2](https://github.com/adafruit/circuitpython/releases/download/2.1.0/adafruit-circuitpython-circuitplayground_express-2.1.0.uf2) for Circuit Playground Express - Plug your board into your computer using USB data cable - [**OPTIONAL**] Reset your board - * e.g. Double-click the small Reset button in the middle of the CPX + - e.g. Double-click the small Reset button in the middle of the CPX -- @@ -762,7 +758,7 @@ esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect -fm ![](img/circuit_playground_greens.jpg) - Check your board is in bootloader mode - * e.g. all of the LEDs turn green in CPX + - e.g. all of the LEDs turn green in CPX -- @@ -771,7 +767,7 @@ esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect -fm ![](img/circuit_playground_cplayboot.gif) - A new disk drive appears - * Name may vary e.g. `CPLAYBOOT` for CPX + - Name may vary e.g. `CPLAYBOOT` for CPX -- @@ -787,9 +783,9 @@ esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect -fm - Download BIN image files e.g. [latest BIN for CPX](https://adafruit-circuit-python.s3.amazonaws.com/index.html?prefix=bin/circuitplayground_express/) - Download [latest version of bossac](https://github.com/shumatech/BOSSA/releases/latest) - * `mingw32` for Windows, `apple-darwin` for Mac OSX, and several `linux` options + - `mingw32` for Windows, `apple-darwin` for Mac OSX, and several `linux` options --- +-- ## Flash with BOSSAC @@ -818,24 +814,25 @@ $ udevadm monitor --udev monitor will print the received events for: UDEV - the event which udev sends out after rule processing -UDEV [1504678146.578976] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2 (usb) -UDEV [1504678146.746860] add /module/usbserial (module) -UDEV [1504678146.747288] add /bus/usb-serial (bus) -UDEV [1504678146.747855] add /bus/usb/drivers/usbserial (drivers) -UDEV [1504678146.748149] add /bus/usb/drivers/usbserial_generic (drivers) -UDEV [1504678146.748241] add /bus/usb-serial/drivers/generic (drivers) -UDEV [1504678146.772466] add /module/ch341 (module) -UDEV [1504678146.772783] add /bus/usb-serial/drivers/ch341-uart (drivers) -UDEV [1504678146.774556] add /bus/usb/drivers/ch341 (drivers) -UDEV [1504678146.774614] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0 (usb) -UDEV [1504678146.775507] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/ttyUSB0 (usb-serial) -UDEV [1504678146.803046] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/ttyUSB0/tty/ttyUSB0 (tty) - -$ picocom /dev/ttyUSB0 -b115200 -``` +UDEV [1504678146.578976] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2 (usb) +UDEV [1504678146.746860] add /module/usbserial (module) +UDEV [1504678146.747288] add /bus/usb-serial (bus) +UDEV [1504678146.747855] add /bus/usb/drivers/usbserial (drivers) +UDEV [1504678146.748149] add /bus/usb/drivers/usbserial_generic (drivers) +UDEV [1504678146.748241] add /bus/usb-serial/drivers/generic (drivers) +UDEV [1504678146.772466] add /module/ch341 (module) +UDEV [1504678146.772783] add /bus/usb-serial/drivers/ch341-uart (drivers) +UDEV [1504678146.774556] add /bus/usb/drivers/ch341 (drivers) +UDEV [1504678146.774614] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0 (usb) +UDEV [1504678146.775507] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/ttyUSB0 (usb-serial) +UDEV [1504678146.803046] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/ttyUSB0/tty/ttyUSB0 (tty) + +\$ picocom /dev/ttyUSB0 -b115200 + +````
-... not always `ttyUSB0` e.g. `ttyACM0` +... not always `ttyUSB0` e.g. `ttyACM0` -- @@ -851,7 +848,7 @@ MicroPython v1.9-8-gfcaadf92 on 2017-05-26; ESP module with ESP8266 Type "help()" for more information. >>> -``` +```` ... The device name might not be `/dev/cu.wchusbserial1410` @@ -871,7 +868,7 @@ Type "help()" for more information. --- -# Excuse me ... +# Excuse me ... # What is MicroPython ? @@ -935,7 +932,7 @@ Written in Python (remember PyPy?) ```sh $ micropython -m upip install micropython-functools -$ ./micropython +$ ./micropython MicroPython v1.7-116-g8dd704b on 2016-04-19; linux version Use Ctrl-D to exit, Ctrl-E for paste mode >>> import functools @@ -1116,7 +1113,7 @@ def foo(self, arg: int) -> int: ## Kits may be missing equipment ------------- +--- If you have trouble finding a component, let us know and we'll get you a replacement @@ -1145,9 +1142,9 @@ Feel free to select the components you like most and complete the challenges tha ## Networking (MicroPython on ESP8266) - WiFi access point (AP) - * ESSID is of the form MicroPython-xxxxxx (MAC address of your device) - * Factory reset Password `micropythoN` - * IP address `192.168.4.1` + - ESSID is of the form MicroPython-xxxxxx (MAC address of your device) + - Factory reset Password `micropythoN` + - IP address `192.168.4.1` - Station interface --- @@ -1186,13 +1183,13 @@ Returned values are: IP address, netmask, gateway, DNS. ## Network configuration - Parameters | Parameter | Type | Description | -|---------------------|------------------------------------------| -| *mac* | bytes | MAC address (bytes) | -| *essid* | string | WiFi access point name (string | -| *channel* | int | WiFi channel (integer) | -| *hidden* | bool | Whether ESSID is hidden | -| *authmode* | enum | Auth mode supported (see `dir(network)`) | -| *password* | string | WiFi access password | +| ---------- | ------ | ---------------------------------------- | +| _mac_ | bytes | MAC address (bytes) | +| _essid_ | string | WiFi access point name (string | +| _channel_ | int | WiFi channel (integer) | +| _hidden_ | bool | Whether ESSID is hidden | +| _authmode_ | enum | Auth mode supported (see `dir(network)`) | +| _password_ | string | WiFi access password | --- @@ -1249,9 +1246,9 @@ import webrepl_setup - Connect to the ESP8266's access point - Launch WebREPL - * Open `webrepl.html` in your browser + - Open `webrepl.html` in your browser - Click the "Connect" button -- Type the password set with `webrepl_setup` when prompted +- Type the password set with `webrepl_setup` when prompted --- @@ -1394,7 +1391,7 @@ Exit loop with `Ctrl-c` ## Built-in LEDs (PyBoard) | Physical name | CPU name | LED description | -|---------------|----------|-----------------| +| ------------- | -------- | --------------- | | P2 | B4 | blue LED | | P3 | A15 | yellow LED | | P4 | A14 | green LED | @@ -1451,7 +1448,7 @@ Now that you've got the basics of LEDs, you can either move on to the next compo ## LED Challenges -*Try to solve them yourself before looking at the solution!* +_Try to solve them yourself before looking at the solution!_ Press ↓ to scroll through the following challenges (and potential solutions) @@ -1482,7 +1479,6 @@ var five = require("johnny-five"); var board = new five.Board(); board.on("ready", function() { - var led1 = new five.Led(10); var led2 = new five.Led(11); var flag = false; @@ -1539,7 +1535,7 @@ board.on("ready", function() { var setting = 0; setInterval(function() { - led.stop(); // If we call pulse, we need to stop it + led.stop(); // If we call pulse, we need to stop it switch (setting) { case 0: led.pulse(); @@ -1558,7 +1554,6 @@ board.on("ready", function() { -- - ### 2. Holiday Lights (Bonuses) 1. Expose a function to the REPL that allows you to switch to the next setting from the REPL @@ -1583,7 +1578,7 @@ board.on("ready", function() { var setting = 0; function changeSetting() { - led.stop(); // If we call pulse, we need to stop it + led.stop(); // If we call pulse, we need to stop it switch (setting) { case 0: led.pulse(); @@ -1599,7 +1594,7 @@ board.on("ready", function() { } this.repl.inject({ - cs: changeSetting // Now we can call cs() from the REPL + cs: changeSetting // Now we can call cs() from the REPL }); }); ``` @@ -1629,7 +1624,6 @@ Using 3 LEDs, count from 0 to 7 in binary as shown below. On represents 1 and of ### Potential Binary Counter Solution (alt 1) - Code ```js - var five = require("johnny-five"); var board = new five.Board(); @@ -1640,9 +1634,9 @@ board.on("ready", function() { var num = 0; setInterval(function() { - var binary = (num).toString(2); + var binary = num.toString(2); - binary.slice(-1) === "1" ? led1.on() : led1.off(); + binary.slice(-1) === "1" ? led1.on() : led1.off(); binary.slice(-2, -1) === "1" ? led2.on() : led2.off(); binary.slice(-3, -2) === "1" ? led3.on() : led3.off(); @@ -1656,7 +1650,6 @@ board.on("ready", function() { ### Potential Binary Counter Solution (alt 2) - Code ```js - var five = require("johnny-five"); var board = new five.Board(); @@ -1669,7 +1662,7 @@ board.on("ready", function() { for (var i = 0; i < leds.length; ++i, mask <<= 1) { var led = led[i]; - num & mask? led.on() : led.off(); + num & mask ? led.on() : led.off(); } num = (num + 1) % 8; @@ -1807,7 +1800,7 @@ Now that you've got the basics of buttons, you can either move on to the next co ## Button Challenges -*Try to solve them yourself before looking at the solution!* +_Try to solve them yourself before looking at the solution!_ Press ↓ to scroll through the following challenges (and potential solutions) @@ -1947,12 +1940,10 @@ Take your servo and add one of the attachments to it ## Save this to a file and run it ```js - var five = require("johnny-five"); var board = new five.Board(); board.on("ready", function() { - var servo = new five.Servo(11); this.repl.inject({ @@ -1999,7 +1990,7 @@ Press ↓ to scroll through the servo challenges ## Servo Challenges -*Try to solve them yourself before looking at the solution!* +_Try to solve them yourself before looking at the solution!_ Press ↓ to scroll through the following challenges (and potential solutions) @@ -2030,7 +2021,6 @@ var five = require("johnny-five"); var board = new five.Board(); board.on("ready", function() { - var servo = new five.Servo(11); var min = servo.range[0]; var max = servo.range[1]; @@ -2065,13 +2055,11 @@ Make pressing the left arrow button rotate the servo one way and pressing the ri ### Potential Arrows Solution - Code ```js - var five = require("johnny-five"); var keypress = require("keypress"); var board = new five.Board(); board.on("ready", function() { - var servo = new five.Servo(11); process.stdin.on("keypress", function(ch, key) { @@ -2095,7 +2083,7 @@ Have the servo sweep while a button is held down ![](img/servo-sweep.gif) --- +-- ### Potential Button Solution - Hardware @@ -2106,7 +2094,6 @@ Have the servo sweep while a button is held down ### Potential Button Solution - Code ```js - var five = require("johnny-five"); var board = new five.Board(); @@ -2135,6 +2122,3 @@ Uh oh! We ran out of slides! Feel free to try out some of the other components i - Thank you for coming! - We'd love your feedback: [bit.ly/cubantech-nodebots-feedback](http://bit.ly/nodebots-feedback) - Please put away kits (you can buy your own [here](http://www.seeedstudio.com/depot/ARDX-The-starter-kit-for-Arduino-p-1153.html)) - - - diff --git a/nodebots-es.md b/nodebots-es.md new file mode 100644 index 00000000000..12d8d151b70 --- /dev/null +++ b/nodebots-es.md @@ -0,0 +1,1047 @@ +## Nodebots con CubanTech (NYJS ;) + +#### Estas diapositivas: [slides.cuban.tech/nodebots.html](http://slides.cuban.tech/nodebots.html) + +--- + +### Información Wifi + +Red: cubantech + +Contraseña: meet-ups + +--- + +### Si aún no lo has hecho, instala Node + +##### [Descarga Node](https://nodejs.org/en/download/) + +##### [Descarga Node de LAN](ftp://qnap01.local/Public/soft/nodejs) + +--- + +- Este taller se basa en gran medida en un taller de [NY-Javascript](http://www.meetup.com/NY-Javascript) (ver [bit.ly/nyjs-nodebots](http://bit.ly/nyjs-nodebots)) +- ... que se basa en gran medida en un taller de [Francis Gulotta](https://twitter.com/reconbot) y [Rick Waldron](https://twitter.com/rwaldron) +- Puede encontrar las diapositivas para ese taller en [gul.ly/3tjj](http://gul.ly/3tjj) +- Puedes inscribirte en uno de sus talleres en la página [Nodebots NYC Meetup page](http://www.meetup.com/nodebots/) + +--- + +## Nuestros lineamientos de la comunidad + +[Ser excelente el uno con el otro](https://github.com/nodeschool/havana/blob/master/Code_of_Conduct.md) + +--- + +Próximos Eventos CubanTech + +- [Encuentros CubanTech](http://meetup.cuban.tech) +- [Encuentros Docker en Cuba](http://docker.cuban.tech) +- [Encuentros Blockstack Cuba](http://blockstack.cuban.tech) +- [SciPyLA 2019](http://conf.scipyla.org) + +--- + +# Muchisimas gracias a nuestro anfitrión + +--- + +## ¿Qué son los Nodebots? + +![](img/johnny-five.png) + +--- + +## JavaScript + Robots = Nodebots + +--- + +# ¡Comencemos! + +--- + +## Nuestro hardware + +[![](img/hardware-kit-closed.jpg)](http://www.seeedstudio.com/depot/ARDX-The-starter-kit-for-Arduino-p-1153.html) + +--- + +## Nuestro hardware + +[![](img/hardware-kit-open.jpg)](http://www.seeedstudio.com/depot/ARDX-The-starter-kit-for-Arduino-p-1153.html) + +--- + +## A los Kits les puede faltar equipo + +--- + +Si tiene problemas para encontrar un componente, háganoslo saber y le conseguiremos un reemplazo. + +--- + +## ¿No funciona? + +## ¡Probablemente hardware! + +--- + +## Componentes que estamos cubriendo + +- LEDs (diodos emisores de luz) +- Botones +- Servos + +--- + +Siéntase libre de seleccionar los componentes que más le gusten y completar los retos que más le interesen. + +--- + +# Empezando + +-- + +## Instalar un nodo si aún no lo ha hecho + +[Descarga node desde Internet](https://nodejs.org/en/download/) + +[Descarga Node desde LAN](ftp://qnap01.local/Public/soft/nodejs) + +-- + +## Crear directorio de proyectos + +```sh +mkdir nodebots +cd nodebots +``` + +-- + +## Instala Johnny Five + +```sh +npm install johnny-five +``` + +--- + +# Para Empezar + +.... con .... + +![](img/docker_logo.png) + +-- + +TODO : Instalación de Document Docker + +--- + +## Estándar Firmata + +- Permite a Johnny-Five comunicarse con el Arduino a través de USB +- La mayoría de los Arduinos ya tienen instalados los Estándar Firmatas de talleres anteriores +- Vamos a comprobar que tu Arduino ya tiene instalado el Estándar Firmata! + +--- + +## Conecta el arduino + +![](img/connecting-arduino.jpg) + +--- + +Crear el fichero + +1. Ve a tu directorio de nodebots +2. Cree un archivo llamado test.js +3. Copie el código que aparece a continuación y guarde + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(13); + + led.blink(500); +}); +``` + +--- + +Ejecute el código + +```sh +node test.js +``` + +--- + +## Este LED debería estar parpadeando cada 0.5 segundos + +![](img/built-in-led.png) + +--- + +Si funciona, ¡continúe! → + +--- + +Si no es así, pulsa ↓ para obtener instrucciones sobre cómo flashear tu Arduino con Estándar Firmata + +-- + +## Cómo flashear tu Arduino con Firmata estándar (mas) + +1. Descargue el[Arduino IDE](https://www.arduino.cc/en/main/software) +2. Asegúrate de que tu Arduino está conectado vía USB +3. Abra el IDE de Arduino +4. Seleccione: Archivo > Ejemplos > Firmata > StandardFirmataPlus +5. Seleccione: Herramientas > Tablero > Arduino/Genuino Uno +6. Seleccione: Herramientas > Puerto > +7. Haga clic en el botón Upload ![](img/arduino-ide-upload-button.png) +8. Vuelva a intentar hacer que el LED parpadee + +--- + +## Componentes que estamos cubriendo + +- LEDs (diodos emisores de luz) +- Botones +- Servos + +--- + +## LEDs + +#### Luz Emision Diodos + +![](img/leds.jpg) + +--- + +## Identificación de Pines LED + +- El pin largo es positiva (y pone en energía) +- El pin corto es negativo (y va a tierra) + +![](img/led-pin-diagram.png) + +--- + +## Construye Esto + +![](img/arduino-led.png) + +--- + +Guarde esto en un archivo y ejecútelo + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + + // "blink" the led in 500ms on-off phase periods + led.blink(500); +}); +``` + +`node blinky.js` + +--- + +## Si tiene éxito, deberías ver esto + +![](img/blinking-led.gif) + +--- + +## Cambio de la frecuencia de parpadeo + +- Probablemente notó que la luz parpadea cada 0,5 segundos. +- Cambie el código para que parpadee a una velocidad diferente y luego vuelva a ejecutarlo para asegurarse de que funciona. +- Si está atascado, presione ↓ para ver una solución potencial + +-- + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + + // "blink" the led in 3000ms on-off phase periods + led.blink(3000); +}); +``` + +`node blinky.js` + +--- + +## El REPL + +- Significa Read Evaluate Print Loop (Leer Evaluar ciclo de impresión ) +- Nos permite escribir el código en nuestro terminal y ver cómo afecta a nuestros robots. + +--- + +## Escribe y ejecuta esto. Luego, continúe con la siguiente diapositiva. + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + + this.repl.inject({ + led: led + }); +}); +``` + +`node led-boss.js` + +--- + +## Escriba estos comandos en el REPL y observe cómo cambia el LED + +``` +> led.on(); + +> led.off(); + +> led.blink(); + +> led.stop(); + +> led.pulse(); +``` + +--- + +## Inyección REPL + +La razón por la que podemos acceder al objeto led en el REPL es por este bit de código en el ejemplo anterior. Expone el objeto led a nuestra sesión REPL. + +```js +this.repl.inject({ + led: led +}); +``` + +--- + +## Breadboards: Cableado sin soldadura + +#### Los Breadboards nos permiten cablear rápidamente los componentes para hacer prototipos + +![](img/breadboard.small.png) + +--- + +## Breadboards: Conexiones eléctricas + +- #### Aquí puedes ver cómo se conectan las diferentes filas y columnas. +- #### Si no está claro, no dudes en buscar en Google o pedirle a un voluntario que te lo explique. + +![](img/breadboard-diagram.small.jpg) + +## Usa tu protoboard y un par de cables (el color no importa) para construir esto + +![](img/arduino-led-breadboard.png) + +--- + +Ahora ejecute uno de sus programas anteriores y asegúrese de que el LED siga parpadeando + +--- + +## Desafíos del LED + +Ahora que tiene los fundamentos de los LEDs, puede pasar al siguiente componente o trabajar en algunos desafíos de los LEDs. + +- Pulse → para pasar al siguiente componente +- Pulse ↓ para desplazarse por los desafíos de los LEDs + +-- + +## Desafíos del LED + +_¡Intenta resolverlos tú mismo antes de mirar la solución!_ + +Pulse ↓ para desplazarse por los siguientes retos (y posibles soluciones) + +1. Múltiples luces +2. Luces navideñas +3. Contador binario + +-- + +### 1. Múltiples luces + +Haga que 2 (o más) luces se alternen parpadeando + +![](img/alternate-blinking.gif) + +-- + +### Solución Potencial de Múltiples Luces - Hardware + +![](img/alternate-blinking-hardware.png) + +-- + +### Solución Potencial de Múltiples Luces - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led1 = new five.Led(10); + var led2 = new five.Led(11); + var flag = false; + + setInterval(function() { + if (flag) { + led1.on(); + led2.off(); + } else { + led1.off(); + led2.on(); + } + + flag = !flag; + }, 500); +}); +``` + +-- + +### 2. Luces navideñas + +#### Haz que un LED (o varios LEDs) pasen por diferentes configuraciones, como hacen algunas luces navideñas. Debería cambiar el ajuste cada pocos segundos. A continuación se muestran algunos ejemplos de configuración. Puede ver un ejemplo en la siguiente diapositiva. + +- Apagado +- Sólido +- Parpadeando +- Pulsos (desvanecimiento hacia adentro y hacia afuera) +- Diferentes velocidades de parpadeo, pulsación o alternancia +- Alternando qué luces están encendidas + +-- + +### 2. Luces navideñas + +![](img/holiday-lights.gif) + +-- + +### Potencial solución de luces navideñas - Hardware + +![](img/holiday-lights-hardware.gif) + +-- + +### Potencial solución para las luces navideñas - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + var setting = 0; + + setInterval(function() { + led.stop(); // Si llamamos al pulso, tenemos que detenerlo + switch (setting) { + case 0: + led.pulse(); + break; + case 1: + led.off(); + break; + case 2: + led.on(); + break; + } + setting = (setting + 1) % 3; + }, 3000); +}); +``` + +-- + +### 2. Luces navideñas (bonos) + +1. Exponer una función a la REPL que le permite cambiar a la siguiente configuración desde la REPL +2. Añada un botón que, al pulsarlo, pase a la siguiente configuración (Nota: debe completar las diapositivas del componente de botones antes de intentarlo). + +-- + +### Potencial solución de Bonus 1 para luces navideñas - Hardware + +![](img/holiday-lights-hardware.gif) + +-- + +### Posible solución de bonificación por luces navideñas 1 - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + var setting = 0; + + function changeSetting() { + led.stop(); // If we call pulse, we need to stop it + switch (setting) { + case 0: + led.pulse(); + break; + case 1: + led.off(); + break; + case 2: + led.on(); + break; + } + setting = (setting + 1) % 3; + } + + this.repl.inject({ + cs: changeSetting // Now we can call cs() from the REPL + }); +}); +``` + +-- + +### Potencial solución de Bonus 2 para luces navideñas + +¡Estás por tu cuenta en esto! + +-- + +### 3. Contador binario + +Usando 3 LEDs, cuente de 0 a 7 en binario como se muestra a continuación. Encendido(On) representa 1 y apagado(off) representa 0. + +![](img/binary-counter.gif) + +-- + +### Solución de contador binario potencial - Hardware + +![](img/binary-counter-hardware.png) + +-- + +### Solución de contador binaria potencial (alt 1) - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led1 = new five.Led(9); + var led2 = new five.Led(10); + var led3 = new five.Led(11); + var num = 0; + + setInterval(function() { + var binary = num.toString(2); + + binary.slice(-1) === "1" ? led1.on() : led1.off(); + binary.slice(-2, -1) === "1" ? led2.on() : led2.off(); + binary.slice(-3, -2) === "1" ? led3.on() : led3.off(); + + num = (num + 1) % 8; + }, 1000); +}); +``` + +-- + +### Solución de contador binaria potencial (alt 2) - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var leds = [new five.Led(9), new five.Led(10), new five.Led(11)]; + var num = 0; + + setInterval(function() { + var mask = 1; + + for (var i = 0; i < leds.length; ++i, mask <<= 1) { + var led = led[i]; + num & mask ? led.on() : led.off(); + } + + num = (num + 1) % 8; + }, 1000); +}); +``` + +-- + +### 3. Contador binario (Bono) + +Permite al usuario introducir un número a través de la REPL y mostrarlo en binario en los LEDs. + +-- + +### Solución potencial de bono de contador binario + +¡Estás por tu cuenta en esto! + +--- + +## Componentes que estamos cubriendo + +- LEDs (diodos emisores de luz) +- Botones +- Servos + +--- + +## Botones + +![](img/buttons.jpg) + +--- + +## Construye esto + +![](img/button-hardware.png) + +--- + +## Guarda esto en un archivo y ejecútalo + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var button = new five.Button(2); + + button.on("press", function() { + console.log("Button Pressed!"); + }); + + button.on("hold", function() { + console.log("Button Held!"); + }); + + button.on("release", function() { + console.log("Button Released!"); + }); +}); +``` + +`node button.js` + +--- + +Intente presionar, soltar y mantener presionado el botón + +Debería ver alguna salida como esta en el REPL + +``` +>> Botón pulsado! +Botón liberado! +Botón pulsado! +Botón liberado! +Botón pulsado! +Botón retenido! +Botón retenido! +Botón liberado! +``` + +--- + +## ¡Añadamos un LED! + +![](img/button-led-hardware.png) + +--- + +## Guarda esto en un archivo y ejecútalo + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + var button = new five.Button(2); + + button.on("press", function() { + led.on(); + }); + + button.on("hold", function() { + led.blink(50); + }); + + button.on("release", function() { + led.stop().off(); + }); +}); +``` + +`node button_led.js` + +--- + +El LED debe encenderse al presionar, apagarse al soltarlo y parpadear al mantenerlo presionado. + +--- + +## Desafíos de los botones + +Ahora que tiene los conceptos básicos de los botones, puede pasar al siguiente componente o trabajar en algunos desafíos de botones. + +- Pulse → para pasar al siguiente componente +- Presione ↓ para desplazarse por los desafíos del botón + +-- + +## Desafíos de los botones + +_¡Intenta resolverlos tú mismo antes de mirar la solución!_ + +Pulse ↓ para desplazarse por los siguientes retos (y posibles soluciones) + +1. Interruptor de luz +2. Clave de acceso +3. Luces navideñas + +-- + +### 1. Interruptor de luz + +Haga que al presionar un botón alternativamente encienda y apague un LED + +-- + +### Solución de interruptor de luz potencial - Hardware + +![](img/light-switch-hardware.png) + +-- + +### Solución de interruptor de luz potencial - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + var button = new five.Button(2); + var on = false; + + button.on("press", function() { + if (on) { + led.off(); + } else { + led.on(); + } + + on = !on; + }); +}); +``` + +-- + +### 2. Clave de acceso + +Dispone de 2 botones y 1 LED. Hágalo de manera que tenga que presionar los botones en cierto orden para encender el LED. + +-- + +### Posible solución de código de acceso - Hardware + +![](img/passcode-hardware.png) + +-- + +### Posible solución de código de acceso - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var led = new five.Led(11); + var button1 = new five.Button(2); + var button2 = new five.Button(4); + + var passcode = "12112"; + var presses = ""; + + button1.on("press", function() { + presses += "1"; + if (presses.indexOf(passcode) > -1) { + led.on(); + } + }); + + button2.on("press", function() { + presses += "2"; + if (presses.indexOf(passcode) > -1) { + led.on(); + } + }); +}); +``` + +-- + +### 3. Luces navideñas + +#### Haz que un LED (o varios LEDs) pasen por diferentes configuraciones, como hacen algunas luces navideñas. Debe cambiar el ajuste cada vez que se pulsa el botón. A continuación se muestran algunos ejemplos de configuración. + +- Apagado +- Sólido +- Parpadeando +- Pulsos (desvanecimiento hacia adentro y hacia afuera) +- Diferentes velocidades de parpadeo, pulsación o alternancia +- Alternando qué luces están encendidas + +-- + +### Potencial solución para las luces navideñas + +¡Estás por tu cuenta en esto! + +--- + +## Componentes que estamos cubriendo + +- LEDs (diodos emisores de luz) +- Botones +- Servos + +--- + +## SERVOS + +![](img/servo.jpg) + +--- + +Toma tu servo y añádele uno de los adjuntos. + +![](img/servo.jpg) + +--- + +## Construye esto + +![](img/servo-hardware.png) + +--- + +## Guarda esto en un archivo y ejecútalo + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var servo = new five.Servo(11); + + this.repl.inject({ + servo: servo + }); +}); +``` + +`node servo.js`s + +--- + +Escribe estos comandos en la REPL y observa cómo reacciona el servo + +```js +> servo.to(10); // Mover a 10 grados + +> servo.to(200); // Mover a 200 grados + +> servo.value; // Obtener la posición actual + +> servo.min(); + +> servo.max(); + +> servo.range; + +> servo.center(); + +> servo.sweep(); +``` + +--- + +## Servo Desafios + +Ahora que tienes los fundamentos de los servos, puedes pasar al siguiente componente o trabajar en algunos desafíos de los servos. + +Pulse → para pasar al siguiente componente +Pulse ↓ para desplazarse por los desafíos de los servos + +-- + +## Servo Desafios + +_¡Intenta resolverlos tú mismo antes de mirar la solución!_ + +Pulse ↓ para desplazarse por los siguientes retos (y posibles soluciones) + +1. Rociador +2. Flechas +3. Botón + +-- + +### 1. Rociador + +Haz que el servo gire de un lado a otro como si fuera un aspersor. + +![](img/sprinkler.gif) + +-- + +### Solución potencial de rociadores - Hardware + +![](img/sprinkler-hardware.png) + +-- + +### Solución potencial de rociadores - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var servo = new five.Servo(11); + var min = servo.range[0]; + var max = servo.range[1]; + var value = min; + + function step() { + servo.to(value); + value = (value + 45) % max; + setTimeout(step, 500); + } + + step(); +}); +``` + +-- + +### 2. Flechas + +Haz que al presionar el botón de flecha izquierda gire el servo en una dirección y al presionar el botón de flecha derecha gire en la otra dirección. + +![](img/servo-arrows.gif) + +-- + +### Solución de Flechas Potenciales - Hardware + +![](img/servo-arrows-hardware.png) + +-- + +### Solución de flechas potenciales - Código + +```js +var five = require("johnny-five"); +var keypress = require("keypress"); +var board = new five.Board(); + +board.on("ready", function() { + var servo = new five.Servo(11); + + process.stdin.on("keypress", function(ch, key) { + if (key && key.name === "left") { + servo.min(); + } else if (key && key.name === "right") { + servo.max(); + } + }); + + process.stdin.setRawMode(true); + process.stdin.resume(); +}); +``` + +-- + +### 3. Botón + +Haz que el servo barra mientras se mantiene pulsado un botón + +![](img/servo-sweep.gif) + +-- + +### Potencial Solución de Botón - Hardware + +![](img/servo-sweep-hardware.png) + +-- + +### Potencial Solución de Botón - Código + +```js +var five = require("johnny-five"); +var board = new five.Board(); + +board.on("ready", function() { + var servo = new five.Servo(11); + var button = new five.Button(2); + + button.on("press", function() { + servo.sweep(); + }); + + button.on("release", function() { + servo.stop(); + }); +}); +``` + +--- + +Uh oh oh! Nos quedamos sin diapositivas! Siéntase libre de probar algunos de los otros componentes de su kit mientras nosotros añadimos más! + +--- + +## Conclusiones + +- Gracias por venir! +- Nos encantaría conocer su opinión: [bit.ly/nodebots-feedback](http://bit.ly/nodebots-feedback) +- Por favor, guarde los kits (puede comprar los suyos propios [aquí](http://www.seeedstudio.com/depot/ARDX-The-starter-kit-for-Arduino-p-1153.html)) diff --git a/translate/digital-electronics-1-es.md b/translate/digital-electronics-1-es.md new file mode 100644 index 00000000000..9692386a347 --- /dev/null +++ b/translate/digital-electronics-1-es.md @@ -0,0 +1,520 @@ +## Electrónica digital + +###### Parte 1 - Circuitos lógicos, puertas, biestables + +#### Estas diapositivas: [slides.cuban.tech/digital-electronics-1.html](http://slides.cuban.tech/digital-electronics-1.html) + +--- + +### Información Wifi + +Red: cubantech + +Contraseña: meet-ups + +--- + +--- + +# Enorme gracias a nuestro anfitrión + +--- + +## Contorno + +- Lógica booleana, puertas, circuitos lógicos. +- Multiplexores +- ALU +- Biestable +- Manos a la obra! Construye un cierre SR + +--- + +# ¡Comencemos! + +--- + +## Nuestro hardware + +[![](img/hardware-kit-closed.jpg)](http://www.seeedstudio.com/depot/ARDX-The-starter-kit-for-Arduino-p-1153.html) + +--- + +## Nuestro hardware + +[![](img/hardware-kit-open.jpg)](http://www.seeedstudio.com/depot/ARDX-The-starter-kit-for-Arduino-p-1153.html) + +--- + +## A los kits les puede faltar equipo + +--- + +Si tiene problemas para encontrar un componente, háganoslo saber y le conseguiremos un reemplazo. + +--- + +## ¿No funciona? + +## ¡Probablemente hardware! + +--- + +## Componentes que estamos cubriendo + +- Puertas lógicas +- Multiplexores +- ALU +- Bistables + +--- + +Siéntase libre de seleccionar los componentes que más le gusten y completar los retos que más le interesen. + +--- + +# Empezando + +## Lógica booleana + +- Operación lógica usando 1's y 0's +- Operaciones de unión, intersección y complemento + +--- + +## Grupos de circuitos lógicos + +- CLC (Circuito Lógico Combinado) + - Asíncrono +- SSC (Circuito Síncrono Secuencial) + - Síncrono, generalmente con una sola señal de reloj + +--- + +# Puertas Basicas + +--- + +## Buffers (regulador) + +![](img/buffer.jpg) + +--- + +## Puerta NOT + +![](img/not-gate.jpg) + +- La versión negada de **_a_** is **_/a_** + +--- + +## Puerta AND + +![](img/and-gate.jpg) + +- **_a_** AND **_b_** = **_a_** \* **_b_** + +-- + +## Propiedades AND + +- **a** \* **a** = **a** +- **a** \* **1** = **a** +- **a** \* **/a** = **0** +- **a** \* **0** = **0** + +--- + +## Puerta OR + +![](img/or-gate.jpg) + +- **_a_** OR **_b_** = **_a_** + **_b_** + +-- + +## Propiedades OR + +- **a** + **a** = **a** +- **a** + **0** = **a** +- **a** + **1** = **1** +- **a** + **/a** = **1** + +--- + +## Puerta XOR + +![](img/xor-gate.jpg) + +- **_a_** XOR **_b_** = **_a_** Ꚛ **_b_** + +-- + +## Propiedades XOR + +- **a** Ꚛ **a** = **0** +- **a** Ꚛ **/a** = **1** +- **a** Ꚛ **0** = **a** +- **a** Ꚛ **1** = **/a** + +--- + +## Puertas universales + +![](img/universal-gates.jpg) + +- **_a_** NAND **_b_** = /(**_a_** \* **_b_**) +- **_a_** NOR **_b_** = /(**_a_** + **_b_**) + +-- + +## ¿Por qué son universales? + +- Las puertas universales pueden sustituir a TODAS las demás puertas +- Puede construir cualquier circuito digital usando sólo puertas NAND o NOR + +-- + +## Las leyes de De Morgan + +- **/**(**a** + **b**) = **/a** \* **/b** +- **/**(**a** \* **b**) = **/a** + **/b** + +--- + +## Creando la verdad de la mesa a partir de un circuito + +-- + +![](img/digital-example-1.jpg) + +-- + +![](img/digital-example-2.jpg) + +-- + +- x = a \* b + +- y = /(b + c) + +-- + +- S = x Ꚛ y + +- S = (a \* b) Ꚛ /(b + c) + +-- + +![](img/digital-example-3.jpg) + +-- + +![](img/digital-example-4.jpg) + +--- + +## Construyendo el circuito desde la tabla de verdad + +![](img/ejemplo-digital-4.jpg) + +-- + +### Expresiones canónicas + +- Suma de productos o producto de sumas +- Cada término de la expresión es un término canónico +- Un término canónico siempre contiene **_TODOS_** las entradas (o las entradas negadas) exactamente una vez + +-- + +## Expresiones canónicas (ejemplo) + +- A, B y C: entradas +- S = (A + B + C) \* (/A + B + /C) +- S = (A \* /B \* /C) + (/A \* /B \* C) + (A \* /B \* C) + +-- + +## Cómo extraer la expresión canónica + +- Decidir si la expresión canónica será: + - una suma de productos + - un producto de sumas + +-- + +## Una suma de productos (minterm) + +- Seleccionar todas las combinaciones con S = 1 +- Si el valor de una entrada en esa combinación es igual a S, entonces aparecerá sin cambios en el término canónico. +- Si es diferente a S, entonces ponemos la versión negada de esa entrada. + +-- + +## Una suma de productos (ejemplo) + +![](img/digital-example-4.jpg) + +-- + +## Una suma de productos (ejemplo) + +### Las combinaciones de ABC con S = 1 + +- 0 0 0 +- 1 0 0 +- 1 1 0 +- 1 1 1 + +-- + +## Una suma de productos (ejemplo) + +Tomemos la combinación **1 0 0** + +- A = 1 (es igual a S => sin cambios) +- B = 0 (no es igual a S => negado) +- C = 0 (no es igual a S => negado) + +Así será el término canónico: **A \* /B \* /C** + +-- + +## Una suma de productos (ejemplo) + +Para la combinación **1 1 0** el término canónico es: **A \* B \* /C** + +- La suma de los productos canónicos de la tabla es: + - (**/A \* /B \* /C**) + (**A \* /B \* /C**) + (**A \* B \* /C**) + (**A \* B \* C**) + +-- + +## El circuito de la expresión canónica: + +![](img/ejemplo-digital-5.jpg) + +-- + +## Un producto de sumas (maxterm) + +- Similar al minterm pero tomamos S = 0 +- El producto de las sumas canónicas para la mesa es: + - (A + B + /C) \* (A + /B + C) \* (A + /B + /C) \* (/A + B + /C) + +-- + +## ¿Cómo decidir si usar expresiones maxterm o minterm? + +- Si la tabla verdadero-falso contiene más de 1 que de 0 en S, utilice maxterm +- De lo contrario, use minterm +- El circuito obtenido por la vía inversa, es también válido pero mayor + +-- + +# Usando sólo puertas universales + +-- + +## Tomemos el último circuito + +![](img/ejemplo-digital-5.jpg) + +-- + +## Añade una pequeña modificación + +![](img/ejemplo-digital-8.jpg) + +-- + +## De aquí.... + +- NOT se puede obtener de la propiedad: + - **/a** = **/(a + a)** +- Usando las leyes de De Morgan.... + +-- + +## Obtenemos esto.... + +![](img/ejemplo-digital-9.jpg) + +--- + +## Desafío #1 + +### Vamos a crear un sumador de 1-bits (medio sumador) + +- A + B + +![](img/ejemplo-digital-7.jpg) + +--- + +## Multiplexores + +- Un multiplexor es un _Selector de canales_ +- Seleccione una de las múltiples entradas y póngala en la salida +- Con las entradas de selección _n_ se pueden direccionar hasta 2n señales. + +![](img/ejemplo-digital-6.jpg) + +-- + +## Multiplexor de 1 bit con 1 entrada de selección + +![](img/ejemplo-digital-10.jpg) + +--- + +## ALU (Unidad Aritmética-Lógica) + +- Es un circuito que le permite _seleccionar_ entre operaciones +- La ALU puede realizar operaciones aritméticas o lógicas + +-- + +## ALU + +![](img/ALU.jpg) + +-- + +## ALU de 1 bit + +- Realiza **XOR**, **AND**, **OR** y **SUMA**. + +![](img/1-bit-ALU.jpg) + +-- + +## Visión general moderna + +- Intel Core i9 utiliza 7 ALU por núcleo +- Cada ALU es diferente dependiendo del uso +- Algunas ALUs sólo realizan operaciones lógicas y operaciones aritméticas simples. +- Algunas otras ALUs realizan operaciones complejas como producto o división. +- Utilizan la microarquitectura Skylake con soporte para hasta AVX-512 +- Las ALUs se utilizan no sólo para variables sino también para calcular el direccionamiento de la memoria. + +--- + +## Bistables + +- Un biestable es un circuito que puede estar en uno de los dos estados durante un tiempo indefinido. +- Puede **_almacenar_** información + +--- + +## Cierres + +- Biestable asíncrono +- Tipo SR +- Tipo D + +-- + +## Cierre SR + +![](img/sr-latch.jpg) + +-- + +## Cierre D + +![](img/d-latch.jpg) + +-- + +## Construyendo un pestillo SR + +![](img/4000_Pinout.jpg) + +-- + +## Esquema de circuito + +- Paso 1 (Suministro de energía) + +![](img/sr-latch-fr1.jpg) + +-- + +## Esquema de circuito + +- Paso 2 (Conexión de las entradas) + +![](img/sr-latch-fr2.jpg) + +-- + +## Esquema de circuito + +- Paso 3 (retroalimentación del pestillo SR) + +![](img/sr-latch-fr3.jpg) + +-- + +## Esquema de circuito + +- Paso 4 (Conexión de los LEDs) + +![](img/sr-latch-fr4.jpg) + +-- + +## Esquema de circuito + +- Resultado + +![](img/sr-latch-fr5.jpg) + +--- + +## Flip-Flop + +- Biestable síncrono +- Tipo D +- Tipo JK +- Tipo T + +-- + +## Flip-Flop tipo D + +- Se basa en el pestillo D +- La entrada **Enable** se sustituye por un detector de flanco ascendente (entrada de reloj). + +-- + +## Flip-Flop tipo D + +![](img/d-flip-flip-flip.jpg) + +--- + +## Aplicaciones de las chancletas + +- Registros +- Registros de cambio +- Diseño de sistemas síncronos (utilizando la técnica de máquinas de estado finito) +- Almacenamiento +- Mostradores +- Microprocesadores + +--- + +## Próximos eventos + +- Electrónica digital (parte 2) + - Mapa de Karnaugh + - Máquina de estado finito + +--- + +## Conclusiones + +- Gracias por venir! diff --git a/translate/docker-intro-es.md b/translate/docker-intro-es.md new file mode 100644 index 00000000000..89c9ced1e7c --- /dev/null +++ b/translate/docker-intro-es.md @@ -0,0 +1,879 @@ + +![Docker logo](img/docker_logo.png) + +## Docker for Developers - Introducción + +#### Festival of Software UNISS] (http://www.uniss.edu.cu), 21 de marzo de 2017 +#### Labs Docker Cuba] (http://docker.cuban.tech), 22 de marzo de 2017 + +###### http://twitter.com/olemislc DIFUNDE LA PALABRA- +###### http://cuban.tech DIFUNDE LA PALABRA- +________________________ + +###### Tráiganlos: [presentación en línea](http://slides.cuban.tech/uniss_20170321.html) /[código fuente](http://git.cuban.tech/slides.cuban.tech) /[docker image](http://hub.docker.com/r/tplcom/docker-presentation/) + +###### Bajo licencia de[Attribution 4.0 International](http://creativecommons.org/licenses/by/4.0/). + +-- + +#### Agradecimientos + +#### Organizadores del Festival de Software UNISS (Gracias) +#### Basado en diapositivas para su presentación en[Python Meetup Thessaloniki](http://www.meetup.com/PyThess/), 15 de abril de 2016 + +###### http://twitter.com/theoploumis DIFUNDE LA PALABRA- + +--- + +#### Who am I? + +- Presidente de SciPyLA 2017 + * Ciencia + Pitón + América Latina +- Mantenedor de algunos plugins de Trac +- Proyecto Apache Bloodhound +- GT Python-Cuba, Fundación Python Software +- Comprometedor de Brython + +-- + +#### Who I used to be? + +- Graduado de ISPJAE (CUJAE) .... hace unos años +- Ámbitos de competencia + * Antivirus + * TVC / ICRT + * Programación (web, escritorio, Android, Smart TV, vestimenta) + * Soporte para DevOps + +-- + +#### Who I used to be? (contd.) + +- Campos de competencia (cont.) + * Bus de campo (Modbus, DNP3, radio, CANbus, Profibus) + * Datos grandes (Apache Hadoop / Spark, Machine learning) + * Makers + + Impresora 3D, CNC, Visualizador + + DIY (Frambuesa Pi, Beaglebone Black, ODROID, MicroPython, Arduino) + +--- + +### Visión general de la charla + +- Historia y antecedentes +- Resumen de acopladores +- Casos de uso de Docker +- Comprensión de Docker +- Ejemplos de acopladores +- Ecosistema portuario +- Próximos eventos + +--- + +### Primer contacto con Docker - PyCon 2014 + +Intro to Docker - PyCon 2014](img/docker.pycon2014.png) + +--- + +#### The origins + +| | | +|:----:|:----:| +| Futuro de los contenedores Linux - PyCon 2013](img/docker.pycon2013.png) | ![Docker in DjangoCon 2013](img/docker.djangocon2013.png) |[Docker in DjangoCon 2013]. +| PyCon 2013 | DjangoCon 2013 | DjangoCon 2013 + +--- + +### Historia de Docker + + - Salomón Hykes ([@solomonstre](http://twitter.com/solomonstre)) + - dotCloud (ahora Docker Inc) + - Marzo de 2013 + - Licencia de Apache 2.0 + - 30.000 estrellas en Github + - 260.000 repositorios públicos en hub.docker.com + - Docker Inc adquiere a todo el mundo TM + - Docker se une a la "[Open Container Initiative](http://www.opencontainers.org/)", junio de 2015 + +--- + +#### What about today? + +| | | +|:-----:|:------:| +| DockerCon 2017](img/dockercon.2017.small.png) | ![PyCon 2017](img/pycon.2017.small.png) |[PyCon 2017](img/pycon.2017.small.png) +| DockerCon 2017 | PyCon 2017 | PyCon 2017 +| 5 pistas, 4 tutoriales, 4 charlas. +| 5.000 asistentes. 3.000 asistentes. + +--- + +#### Docker Birthday #4 + +![Cumpleaños de Docker #4](img/Docker-bday-4.jpg) + +--- + +#### Let me let me ask you + +- ¿Quién sabe lo de[Docker](http://docker.com)? +- ¿Quién utiliza Docker para el desarrollo? +- ¿Quién utiliza Docker en la producción? +- ¿Quién lo intentó pero no pudo hacerlo? + +--- + +### ¿Qué es Docker? + +> Docker es una plataforma abierta para desarrollar, enviar y ejecutar aplicaciones. + +> Docker le permite empaquetar una aplicación con todas sus dependencias en una unidad estandarizada para el desarrollo de software. + +-- + +### Docker en el ecosistema de las TIC + +Virtualización](img/app.containers.png) + +--- + +### Docker contra VMs + +!Docker vs virtualización tradicional](img/vms_vs_containers.jpg) + +--- + +### Beneficios portuarios + + - Rápido (despliegue, migración, reinicio) + - Seguro + - Ligero (ahorra disco y CPU) + - Código Abierto + - Software portátil + - Microservicios e integraciones (APIs) + - Simplificar DevOps + - Capacidades de control de versiones + +-- + +#### Micro-what ## Servicios? + +Arquitectura de microservicios](img/microservicios.png) + +--- + +#### Common Docker usages + + - Entorno Sandbox (desarrollar, probar, depurar, educar) + - Integración e implementación continuas + - Escalar aplicaciones + - Colaboración para el desarrollo + - Configuración de la infraestructura + - Desarrollo local + - Aplicaciones de varios niveles + - PaaS, SaaS + +###### Ver los resultados de la[encuesta de 2016] (http://www.docker.com/survey-2016) + +-- + +### Entorno de desarrollo + +Entorno de desarrollo](img/devenv.jpg) + +-- + +### Educación JupyterHub software + +![JupyterHub](img/jupyterhub.gif) + +-- + +### Educación - Despliegue de JupyterHub + +![Componentes JupyterHub](img/jupyterhub-setup.png) + +-- + +### Integración continua + +Integración continua con Docker](img/dagda3.jpg) + +-- + +### Entrega continua - Joomla + +Entrega continua de Joomla](img/joomla-docker-cd.jpg) + +-- + +### Escalado - de 10 a 1000 + +Descripción del problema de Apache Mesos](img/dockercon14_mesos.1.png) + +###### Benjamin Hindman (Twitter) - DockerCon 2014[video](http://youtu.be/F1-UEIG7u5g) + +-- + +### Escalado - regiones de servidores de aplicaciones + +Regiones del servidor de aplicaciones Apache Mesos](img/dockercon14_mesos.2.png) + +###### Benjamin Hindman (Twitter) - DockerCon 2014[video](http://youtu.be/F1-UEIG7u5g) + +-- + +#### Scaling - ouch! + +!Mensaje de correo electrónico de Apache Mesos](img/dockercon14_mesos.3.png) + +###### Benjamin Hindman (Twitter) - DockerCon 2014[video](http://youtu.be/F1-UEIG7u5g) + +-- + +### Escala - problema amplificado + +![Apache Mesos - problema amplificado](img/dockercon14_mesos.4.png) + +###### Benjamin Hindman (Twitter) - DockerCon 2014[video](http://youtu.be/F1-UEIG7u5g) + +-- + +### Escala - Utilización + +![Utilización de Apache Mesos](img/dockercon14_mesos.5.png) + +###### Benjamin Hindman (Twitter) - DockerCon 2014[video](http://youtu.be/F1-UEIG7u5g) + +-- + +### Escalado - Administrador de clústeres + +! arquitectura Apache Mesos](img/dockercon14_mesos.6.png) + +###### Benjamin Hindman (Twitter) - DockerCon 2014[video](http://youtu.be/F1-UEIG7u5g) + +-- + +### Escala - Ejecución + +![Asignación de recursos de Apache Mesos](img/dockercon14_mesos.7.png) + +###### Benjamin Hindman (Twitter) - DockerCon 2014[video](http://youtu.be/F1-UEIG7u5g) + +-- + +### Escalado - Apache Mesos soporta Docker desde 2014 + +Apache Mesos ](img/dockercon14_mesos.8.png) + +###### Benjamin Hindman (Twitter) - DockerCon 2014[video](http://youtu.be/F1-UEIG7u5g) + +-- + +### Contenedores en la plataforma Google Cloud Platform + +| | | +|-----|-----| +Centro de datos de Google](img/google.datacenter.png) | ![GCE soporta Docker](img/gce.docker.png) ||[GCE soporta Docker](img/gce.docker.png) + +- Todo en Google se ejecuta en un contenedor + *[LMCTFY](https://github.com/google/lmctfy) y Docker +- 2 mil millones de envases por semana + +-- + +### Grandes datos impulsados por Docker + +![BlueData Epic Platform](img/bluedata.epic.png) + +----------------- + +###### Joe Beda, ingeniero principal de software, Google Cloud Platform +###### GlueCon - 22 de mayo de 2014 + +--- + +### La tecnología detrás de Docker + + - Linux[x86-64](http://www.wikiwand.com/en/X86-64) + - [Ir](http://golang.org/) idioma + - Arquitectura[Cliente - Servidor](http://www.wikiwand.com/en/Client%E2%80%93server_model) (deamon) + - Union file systems ([UnionFS](http://www.wikiwand.com/en/UnionFS): AUFS, btrfs, vfs, etc.) + - [Namespaces](http://en.wikipedia.org/wiki/Cgroups#NAMESPACE-ISOLATION) (pid, net, ipc, mnt, uts) + - Grupos de control ([cgroups](http://www.wikiwand.com/en/Cgroups)) + - Formato de contenedor ([libcontainer](http://github.com/opencontainers/runc/tree/master/libcontainer "Libcontainer proporciona una implementación nativa de Go para crear contenedores con espacios de nombres, cgroups, capacidades y controles de acceso al sistema de archivos. Permite gestionar el ciclo de vida del contenedor realizando operaciones adicionales tras la creación del contenedor."))) + +###### Ver más en[Understanding docker] (http://docs.docker.com/engine/understanding-docker/) + +-- +#### Código de muelle escrito en Go + +| | | +|----|----| +| | [![Docker and Go](img/golang_docker.jpg)](http://golang.org/) | | [![Golang Book](img/golang.book.png)](http://golang.org/) | + +-- + +### Los namespaces de Linux + +![Linux namespaces](img/ns.jpg) + +-- + +### Asignación de recursos con cgroups + +![ejemplo de asignación de cgroups](img/cgroups.1.gif) + +-- + +### Asignación de recursos con cgroups + +![ejemplo de asignación de cgroups](img/cgroups.2.1.png) + +--- + +### La arquitectura Docker + +![Arquitectura de Docker](img/architecture.svg) +###### Ver más en[Understanding docker] (http://docs.docker.com/engine/understanding-docker/) + +--- + +### Componentes de la rampa + + - (Docker) cliente + - demonio + - máquina + - artificio + - formar + - enjambrar + - registro + +--- + +### Cliente portuario + +Es la principal interfaz de usuario de Docker. Acepta comandos del usuario +y se comunica de un lado a otro con un demonio Docker. + +--- + +### El demonio Docker + +![Docker libs](img/docker-langs.small.png) + +Funciona en una máquina anfitriona. El usuario no interactúa directamente con el demonio, +sino a través del cliente Docker con la api o tomas RESTful. + +--- + +#### Docker engine + +Un Cliente con un demonio como también como herramienta de composición de docker. Se suele denominar simplemente "docker". + +--- + +### Máquina portuaria + +![Logotipo de la máquina acopladora](img/docker_machine.png) + +Una herramienta que facilita enormemente la creación de hosts Docker en su ordenador, +en proveedores de cloud computing y dentro de su propio centro de datos. +Crea servidores, instala Docker en ellos y configura el cliente para que hable con ellos. + +--- + +#### Docker compose + +![Docker componer logo](img/docker_compose.png) + +Una herramienta para definir y ejecutar aplicaciones complejas con Docker +(por ejemplo, una aplicación multi-contenedor) con un solo archivo. + +-- + +### Ejemplo de orquestación de contenedores + +![Docker componer ejemplo](img/nginx_flask_postgres_docker.png) + +--- + +#### Docker swarm + +![Logotipo del enjambre del muelle](img/docker_swarm.png) + +Una herramienta de agrupación nativa para Docker. Enjambres de piscinas juntos varios Docker +y los expone como un único host Docker virtual. Se puede escalar a múltiples hosts. + +--- + +### Distribución portuaria + +![Logotipo de distribución portuaria](img/docker_distribution.png) + +Un servicio (alojado) que contiene repositorios de imágenes que responden a la API del Registro. + +--- + +### Pasos de un flujo de trabajo Docker + +``` +docker run -i -t -d ubuntu:15.04 /bin/bash +``` + + - Tira de la ubuntu:15.04[imagen] (http://docs.docker.com/engine/userguide/containers/dockerimages/ "Una capa de sólo lectura que es la base de su contenedor. Puede tener una imagen principal para abstraer la instantánea más básica del sistema de archivos") del[registro] (http://docs.docker.com/registry/ "The central place where all publicly published images live. Puedes buscarlo, subir tus imágenes allí y cuando sacas una imagen de un docker, viene el repositorio/hub.") + - Crea un nuevo[contenedor] (http://docs.docker.com/engine/userguide/storagedriver/imagesandcontainers/ "A runnable instance of the image, basically it is a process isolated by docker that runs on top of the filesystem that an image provides.") + - Asigna un sistema de ficheros y monta una capa de lectura-escritura[layer] (http://docs.docker.com/engine/reference/glossary/#filesystem "A set of read-only files to provision the system. Piensa en una capa como una instantánea de sólo lectura del sistema de archivos.") + - Asigna una[interfaz de red/puente] (http://www.wikiwand.com/en/Bridging_%28networking%29 """) + - Configura una[dirección IP] (http://www.wikiwand.com/en/IP_address "Una dirección de protocolo de Internet (dirección IP) es una etiqueta numérica asignada a cada dispositivo (por ejemplo, ordenador, impresora) que participa en una red informática que utiliza el protocolo de Internet para la comunicación"). + - Ejecuta un proceso que usted especifica (```` /bin/bash ```) + - Captura y proporciona salida de la aplicación + +--- + +#### The docker image + +| | | +|-----|-----| +| Arquitectura Docker](img/arquitectura.small.png) | ![ubuntu:15.04 imagen](img/image-layers.jpg "Una capa de sólo lectura que es la base de su contenedor. Puede tener una imagen padre para abstraer la instantánea más básica del sistema de archivos. Cada imagen Docker hace referencia a una lista de capas de sólo lectura que representan las diferencias del sistema de archivos. Las capas se apilan una encima de otra para formar una base para el sistema de archivos raíz de un contenedor.) | + +--- + +#### The docker container + +| | | +|-----|-----| +| Arquitectura Docker](img/arquitectura.small.png) | ![contenedor usando imagen ubuntu:15.04](img/container-layers.jpg "Una instancia ejecutable de la imagen, básicamente es un proceso aislado por docker que se ejecuta sobre el sistema de archivos que proporciona una imagen. Para cada contenedor hay una capa nueva, delgada y grabable - capa de contenedor - en la parte superior de la pila subyacente (imagen)"). | + +-- + +#### Union filesystem explained + +![Explicación de UFS](img/ufs.png) + +--- + +#### The Dockerfile + +> Un Dockerfile es un documento de texto que contiene todos los comandos que un usuario puede llamar en la línea de comandos para crear una imagen. + + - [Esta presentación](Dockerfile) + - [Dockerfile con comentarios en línea](http://github.com/cubantech/docker-presentation/blob/gh-pages/examples/dockerfile/Dockerfile) sólo para la educación + - [Referencia del archivo del muelle] (http://docs.docker.com/engine/reference/builder/) en los muelles del muelle + - Archivos portuarios oficiales ([rieles](http://github.com/docker-library/rails/blob/master/Dockerfile),[nodejs](http://github.com/ReadyTalk/nodejs-docker/blob/master/base/Dockerfile),[django](http://github.com/docker-library/django/blob/master/3.4/Dockerfile),[Drupal](http://github.com/docker-library/drupal/blob/master/8.1/fpm/Dockerfile)) + +-- + +#### Dockerfile for these slides + +``` +DE bitnami/apache +MAINTAINER Olemis Lang + +# Añade todo el repositorio. +AGREGAR /opt/bitnami/apache/htdocs/ + +# Configure esta opción como ruta inicial cuando inicie sesión a través de ssh. +WORKDIR /opt/bitnami/apache/htdocs/ +``` + +-- + +### Árboles de imágenes de Docker + +Árbol de imágenes del muelle](img/docker_images.gif) + +--- + +#### Common Docker Commands + +``` +// Información general +man docker // man docker-run +docker help // docker help run +información del muelle +versión portuaria +docker network ls + +// Imágenes +docker images // docker[IMAGE_NAME] +docker pull[IMAGE] // docker push[IMAGE] + +// Contenedores +carrera de muelle +docker ps // docker ps -a, docker ps -l +parada/arranque/rearranque de la base[CONTAINER]. +estadísticas portuarias[CONTENEDOR] +docker top[CONTAINER] +puerto de atraque[CONTAINER] +inspección de muelle[CONTENEDOR] +docker inspect -f "{{.State.StartedAt }}" [CONTENEDOR] +docker rm[CONTENEDOR] + +``` + +--- + +### Ejemplos de Docker + +- SSH en un contenedor +- Construir una imagen +- Docker[Volumen](http://docs.docker.com/engine/userguide/containers/dockervolumes/) +- Contenedores[Linked](http://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/) +- Utilizando[docker-compost] (http://docs.docker.com/compose/) +- Contenedores de báscula con docker-compost +- Compartir una imagen (compartir esta presentación) +- Empaquetar una aplicación con su entorno +- Pantalla y sonido dentro de los contenedores (x-forward) + +-- + +#### Ejemplo: SSH en un contenedor + +``` +docker pull ubuntu +docker run -it --nombre ubuntu_ejemplo ubuntu /bin/bash +``` + +-- + +#### Ejemplo: Ejecute Jenkins de forma autónoma + +Vamos a correr la[imagen oficial de Jenkins] (http://hub.docker.com) + +``` +docker pull jenkins + +// Pruébalo +docker run -d -p 8098:8080 --nombre jenkins_example_1 jenkins +http://localhost:8098 DIFUNDE LA PALABRA- +``` + +-- + +#### Ejemplo: Construir una imagen + +Construyamos una[imagen de Jenkins] (http://github.com/komljen/dockerfile-examples/blob/master/jenkins/Dockerfile) + +``` +cd ~/Docker-presentación +clon de git git@github.com:komljen/dockerfile-examples.git.git +cd dockerfile-ejemplos/jenkins +docker build -t jenkins-local. + +// Pruébalo +docker run -d -p 8099:8080 --nombre jenkins_example_2 jenkins-local +Abierto http://localhost:8099 +``` + +-- + +#### Ejemplo: Volumen del acoplador + +Usemos[servidor Apache](http://bitbucket.org/EdBoraas/apache-docker/src/) + +``` +cd ~/Docker-presentación +mkdir apache-ejemplo +cd apache-ejemplo + +docker pull bitnami/apache +docker run --nombre apache_volume_example \ + -p 8180:80 -p 443:443 \ + wWw.Subs-Team.Tv $(pwd):/opt/bitnami/apache/htdocs/ \ + -d bitnami/apache + +// Crear localmente un archivo index.html +echo "Funciona usando mount." >> index.html + +Abra http://localhost:8180 para ver el archivo html +``` + +-- + +### Ejemplo: Drupal + MariaDB con aislamiento de red + +Bitnami ofrece contenedores preconfigurados y de cero confinamiento + +``` +docker pull bitnami/mariadb:latest bitnami/drupal:latest + +red de acopladores crear drupal-tier +docker run -d --nombre mariadb --net drupal-tier bitnami/mariadb:más reciente +docker run -d -p 8081:80 -p 443:443 --nombre drupal --net drupal-tier bitnami/drupal:más reciente +``` + +-- + +#### Ejemplo: Contenedores Docker Link + +Vamos a crear una aplicación[Drupal app](http://hub.docker.com/_/drupal/) (apache, php, mysql, drupal) + +``` +cd ~/Docker-presentación +ejemplo de drupal-link de mkdir +cd ejemplo de drupal-link + +docker pull drupal:8.0.6-apache +docker pull mysql:5.5 + +// Poner en marcha un contenedor para mysql +docker run --nombre mysql_example \ + -e MYSQL_ROOT_PASSWORD=root \ + -...MYSQL_DATABASE=drupal. + DIFUNDE LA PALABRA- + -...MYSQL_PASSWORD=drupal. + -d mysql:5.5 + +// Iniciar un contenedor de Drupal y enlazarlo con mysql +// Uso: --...enlace[nombre o id]:alias +docker run -d --nombre drupal_example \ + -p 8280:80 \ + --DIFUNDE LA PALABRA- + drupal:8.0.6-apache + +Abra http://localhost:8280 para continuar con la instalación. +// En el uso del host db: mysql + +// Hay una conexión apropiada +docker inspect -f "{{.HostConfig.Links }}" drupal_example +``` + +-- + +#### Ejemplo: Uso de Docker Compose + +Vamos a crear una aplicación Drupal con[docker-compos.yml](http://github.com/cubantech/docker-presentation/blob/gh-pages/examples/docker-compose/docker-compose.yml) + +``` +cd ~/Docker-presentación +git@github.com:cubantech/docker-presentation.git DIFUNDE LA PALABRA- +cd docker-presentación/ejemplos/docker-compuesto + +// Ejecute docker-composition usando el docker-composition.yml +gato docker-composite.yml +docker-compone -d +``` + +-- + +#### Ejemplo: Compartir una imagen pública + +``` +cd ~/Docker-presentación +git@github.com:cubantech/docker-presentation.git DIFUNDE LA PALABRA- +cd docker-presentación + +docker pull bitnami/apache +docker build -t olemis/docker-presentation . + +// Pruébalo +docker run -itd --nombre docker_presentation \ + -p 8480:80 \ + olemis/docker-presentación + +Abrir http://localhost:8480, deberías ver esta presentación + +// Empújalo en el hub.docker.com +docker push olemis/docker-presentación +``` + +-- + +#### Ejemplo: Exportar/Guardar/Cargar, etc. + +``` +docker pull nimmis/alpine-apache +docker run -d --nombre apache_example \ + nimmis/alpine-apache + +// Crear un archivo dentro del contenedor. +Ver http://github.com/nimmis/docker-alpine-apache para más detalles. +docker exec -ti apache_example \ + /bin/sh -c 'mkdir /test && echo "This is it." >> /test/test.txt' + +// Pruébalo. Deberías ver el mensaje: "Esto es todo." +docker exec apache_example cat /test/test.txt + +// Confirme el cambio. +docker commit apache_export_example myapache:latest + +// Cree un nuevo contenedor con la nueva imagen. +docker run -d --nombre myapache_ejemplo myapache + +// Debería ver la nueva carpeta/archivo dentro del contenedor myapache_example. +docker exec myapache_example cat /test/test.txt + +// Exportar el contenedor como imagen +cd ~/Docker-presentación +docker exportar myapache_example > myapache_example.tar + +// Importar una nueva imagen desde los archivos exportados +cd ~/Docker-presentación +docker importar myapache_example.tar myapache:nuevo + +// Guardar una nueva imagen como tar +docker save -o ~/Docker-presentation/myapache_image.tar myapache:new + +// Cargar una imagen desde el archivo tar +docker load < myapache_image.tar + +``` + +-- + +#### Ejemplo: GUI con Docker + +Ver ejemplos en[hub.docker.com/u/jess](http://hub.docker.com/u/jess/) + +``` +// Antes de empezar, debemos permitir el acceso a todos en el Servidor X (localmente) +// De lo contrario, los siguientes contenedores nunca arrancarán y no podrán utilizar x11 +xhost + + +// Libreoffice +docker run -d \ + wWw.Subs-Team.Tv /etc/localtime:/etc/localtime:ro \ + wWw.Subs-Team.Tv/.X11-unix:/tmp/.X11-unix \ + -e DISPLAY=unix$DISPLAY \ + -e GDK_SCALE \ + -e GDK_DPI_SCALE \ + --nombre libreoffice \ + jess/libreoffice + +// SublimeTexto 3 +docker run -it \ + wWw.Subs-Team.Tv $HOME/.config/sublime-text-3/:/root/.config/sublime-text-3 \\ + wWw.Subs-Team.Tv/.X11-unix:/tmp/.X11-unix \ + -e DISPLAY=$DISPLAY \ + --nombre sublime_text \ + jess/sublime-text-3 + +// Audacia (sonido en el contenedor de la rampa) +docker run -d \ + wWw.Subs-Team.Tv /etc/localtime:/etc/localtime:ro \ + wWw.Subs-Team.Tv/.X11-unix:/tmp/.X11-unix \ + -e DISPLAY=unix$DISPLAY \ + -e QT_DEVICE_PIXEL_RATIO \ + --...dispositivo /dev/snd. + --group-add audio \ + --nombre audacia \ + jess/audacity + +// Desactivar el acceso a x11 +xhost - + +``` + +--- + +### Las puntas de los muelles + +Se conocen las mejores prácticas (véase una lista en[examples/tips](http://github.com/cubantech/docker-presentation/tree/gh-pages/examples/tips)]) + +- Optimice los contenedores (consulte[fromlatest.io](http://www.fromlatest.io/) y[imagelayers.io](http://imagelayers.io)) +- Crea tu propia base diminuta +- Los contenedores no son máquinas virtuales +- Pila completa de Imágenes VS 1 proceso por Contenedor +- Crea tu registro privado +- Crear comandos de acceso directo +- Utilice plantillas docker-compos.yml (vea por qué en[lorry.io](http://lorry.io/)) +- Ten en cuenta la versión del agente de la dársena hub.docker.com + +--- + +### La guerra de los Dockers + +| Tipo | Software | Software +|:----:|----------| +| Clustering/orchestration |[Swarm](http://docs.docker.com/swarm/),[Kubernetes](http://kubernetes.io/),[Marathon](http://mesosphere.github.io/marathon/),[MaestroNG](http://github.com/signalfx/maestro-ng),[decking](http://decking.io/),[shipyard](http://shipyard-project.com/),[Apache Mesos](http://mesos.apache.org) | +| Registros portuarios |[Portus](http://port.us.org/),[Docker Distribution](http://github.com/docker/distribution),[hub.docker.com](http://hub.docker.com),[quay.io](http://quay.io),[Google container registry](http://cloud.google.com/tools/container-registry/),[Artifactory](http://www.jfrog.com/artifactory/),[projectatomic.io](http://www.projectatomic.io/) |]. +| PaaS con Docker |[Rancher](http://rancher.com/),[Tsuru](http://tsuru.io/),[dokku](http://github.com/dokku/dokku),[flynn](http://flynn.io/),[Octohost](http://octohost.io/),[DEIS](http://deis.io/) | +OS hecho de Contenedores |[RancherOS](http://rancher.com/rancher-os/) | | Containers |[RancherOS] (http://rancher.com/rancher-os/) + +-- + +### Benchmarking y estadísticas + +![Docker vs Kubernetes vs Amazon ECS](img/docker-orchestration-survey.png) + +###### Ver los resultados de la[encuesta de 2016] (http://www.docker.com/survey-2016) + +--- + +### Alternativas Docker + +- [Rocket, rkt](http://github.com/coreos/rkt) +- [Contenedores Linux, LXC](http://linuxcontainers.org/) +- Hipervisor de contenedores Linux, LXD] (http://www.ubuntu.com/cloud/lxd) +- [Cárceles BSD] (http://www.freebsd.org/doc/handbook/jails.html) +- [Zonas Solaris](http://oracle.com/solaris) +- [puente levadizo] (http://research.microsoft.com/en-us/projects/drawbridge/) + +--- + +#### En vez de recursos + +![Usando Docker](img/using.docker.png) + + - [Awesome Docker](http://github.com/veggiemonk/awesome-docker) (lista de recursos y proyectos de Docker) + - [Hoja de trucos de Docker](http://github.com/wsargent/docker-cheat-sheet) + - [Docker in Practice](http://www.manning.com/books/docker-in-practice),[The Docker Book](http://www.dockerbook.com/),[Using Docker](http://bit.ly/using-docker) + - [alias de Docker/abreviaturas] (http://github.com/cubantech/docker-presentation/tree/gh-pages/examples/shortcuts/docker-aliases.sh) + - Docker[estudios de casos](http://www.docker.com/customers) + +--- + +### Eventos futuros - Docker Cuba + +| | | +|-----|-----| +| | [![Docker Cuba](img/dockercuba.logo.png)](http://docker.cuban.tech) | | [![Join us!](img/qr.volunteer.es.png)](http://forms.cuban.tech/volunteer/es) || + +####### Únete a nosotros -[forms.cuban.tech/volunteer/es](http://forms.cuban.tech/volunteer/es) + + - Encuentros en Cuba Docker[docker.cuban.tech](http://docker.cuban.tech) + * Celebración del cumpleaños de Docker #4 en todas las provincias. + +--- + +### Eventos futuros - SciPyLA 2017 + +| | | +|-----|-----| +| | [![SciPyLA 2017](img/scipyla.h.png)](http://scipyla.org/conf/2017) | | [![Emerging Computing Technologies](img/scipyla2017.tech.png)](http://scipyla.org/conf/2017/tracks/tech) | + + - [Taller de Tecnologías Informáticas Emergentes] (http://scipyla.org/conf/2017/tracks/tech) + * Infraestructura para la investigación reproducible + * .... con Docker! \o/ + +-- + +### Convocatoria de ponencias / revisores + +Convocatoria de ponencias](img/scipyla2017.cfp.png) + +- Fecha límite de presentación 30 de septiembre de 2017 +- [Aplicar como árbitro](http://scipyla.org/conf/2017/forms/reviewers/) +- [Instrucciones para los autores] (http://scipyla.org/conf/2017/tracks/tech) + +-- + +#### Participate + +- Envía tus charlas / talleres[bit.ly/scipyla2017-actividades-tech](http://bit.ly/scipyla2017-actividades-tech) +- [Enviar carteles](http://scipyla.org/conf/2017/forms/poster) + +--- + +### ¿Preguntas? + +!Pythons sobre Docker!](img/docker_logo.png) + +[Revisar esta presentación] (http://goo.gl/lkau9t) + +> Siguiente: Docker en producción, Escalado, Registros privados, PaaS. + +###### En esta presentación he utilizado[oh my zsh](http://ohmyz.sh/),[docker 17.03](http://github.com/docker/docker/releases/tag/v1.12.5),[wharfee](http://github.com/j-bennet/wharfee) y[dry](http://github.com/moncho/dry). diff --git a/translate/pandas-ddj-es.md b/translate/pandas-ddj-es.md new file mode 100644 index 00000000000..f3f9638f874 --- /dev/null +++ b/translate/pandas-ddj-es.md @@ -0,0 +1,273 @@ +## Introducción a pandas y Jupyter Notebook +##### *para manipulación de datos en periodismo* + +#### [CubanTech Meetup #16](http://meetup.cuban.tech/events/240372001/), 29 de julio de 2017 + +###### [Barbara Maseda](https://www.linkedin.com/in/barbara-maseda-8006935a) / [@barbaramaseda](http://twitter.com/barbaramaseda) +###### [Rachel Domínguez](https://www.linkedin.com/in/rachel-dom%C3%ADnguez-b5271891/) / [@racheldrojas](http://twitter.com/racheldrojas) +###### [Olemis Lang](http://www.linkedin.com/in/olemis) / [@olemislc](http://twitter.com/olemislc) +###### [The CubanTech Group](http://cuban.tech) / [@TheCubanTech](http://twitter.com/TheCubanTech) + +-- + +###### Esta presentación ha sido creada con [reveal.js](https://travis-ci.org/hakimel/reveal.js). Descargue las [diapositivas](http://slides.cuban.tech/pandas-ddj.html) / [código fuente](http://github.com/cubantech/slides.cuban.tech) + +###### Licencia [Attribution 4.0 International](http://creativecommons.org/licenses/by/4.0/). + +--- + +* Periodismo de datos +* Jupyter Notebooks +* Python (pandas) + + +--- + +### Programa para el día de hoy + +- Intro al evento +- Periodismo de datos y programación + * Aplicaciones de Python en periodismo +- Jupyter Notebook +- Introducción a pandas + +-- + +### Introducción a pandas +- Conceptos básicos +- Operaciones básicas +- Importación y exploración de datos +- Procesamiento y análisis de datos +- Actividad práctica +- Algunas operaciones más avanzadas + * Tablas dinámicas + * Crear un data frame desde cero + * Combinar conjuntos de datos + +--- + +### Proceso de producción + +![](img/ddj workflow 1.jpg) + + *Etapas de la producción de un proyecto de periodismo de datos según Aitamurto, Sirkkunen y Lehtonen (2011)* + + +-- + +![](img/data journalism workflow guardian.jpg) + + *Flujo de trabajo en periodismo de datos. Mark McCormick. Tomado de “A data journalism workflow” de Simon Rogers (2013)* + +-- + + ![](img/wj guardian 1.jpg) + + -- + + ![](img/wj guardian 2.jpg) + +--- + +### Formato de datos + +* pdf +* txt, odf, doc, +* CSV, TSV, *SV +* xls, xlsx, ods +* Html, xml +* Jpeg, png, tiff +* gis +* db +* Json +* geojson, osm, kml + +--- + +### Tamaño de los datos + +Hojas de cálculo limitadas a procesar 1 millón de filas + * Excel (1.048.576 x 16384) + * Calc (1.048.576 x 1024) + + +-- + +### Tamaño de los datos + +* 2015 - Emails del servidor privado de Clinton - 50,547 páginas de documentos - 7,570 enviados por Clinton +* 2015 - Panama Papers +* 2016 - Informe Chilcot +2.6 millones de palabras + +-- + +### Tamaño de los datos + + ![](img/panama papers.jpg) + +![](img/panama papers.png) + +--- + +![](img/1500625593_language_rank_2017.jpg) + +Ranking del grupo de investigación IEEE Spectrum. +Ver metodología [aquí](http://spectrum.ieee.org/ns/IEEE_TPL_2017/methods.html). + + +-- + +![](img/CkWqkdVXEAAXqLI.jpg large.jpg) + +--- + +##### Principales librerías de Python para análisis de datos en 2017, según kdnuggets.com + +* Numpy (Commits: +15000, Contributors: 522) +* SciPy (Commits: +17000, Contributors: 489) +* Pandas (Commits: 15089, Contributors: 762) +* Matplotlib (Commits: +21000, Contributors: 588) +* Seaborn (Commits: 17000, Contributors: 71) +* Bokeh (Commits: +15000, Contributors: 223) + +-- + +![](img/Screenshot_2017-07-28-12-20-49.png) + + +-- + +![](img/Screenshot_2017-07-28-12-18-24.png) + + +--- + +##### Lenguajes de programación populares entre periodistas + +* Python +* R +* JavaScript +* Pearl +* PHP +* Ruby + +--- + +##### Ventajas de Python para periodistas + +* Versátil +* Fácil de aprender +* Intuitivo / Sintaxis clara +* Buena documentación +* Muchas opciones de librerías +* Opciones de librerías para integración con tecnologías de terceros +* Amplia adopción en la industria + +-- + +##### Desventajas + +* Curva de aprendizaje +* Incompatibilidad de versiones 2.x y 3.x + +--- + +##### Liberías de Python populares en periodismo + +* pandas +* numpy +* matplotlib +* re +* BeautifulSoup +* scrapy, tweepy +* NLTK +* SciKit-learn + +--- + +##### pandas + +![](img/python_pandas.jpg) + +### pandas = «PANel DAta» + +*Concepto de Estadística y Econometría que designa datos multidimensionales medidos en diferentes intervalos de tiempo* + +-- + +### pandas + +| | | +|::::|::::| +|Autor original | Wes McKinney | +|Desarrolladores | Comunidad | +|Última versión estable | 0.20.2/ 4 junio de 2017 | +|Respositorio | https://github.com/pydata/pandas | +|Lenguaje | Python | +|Sistema operativo | Multiplataforma | +|Licencia | BSD | +|Sitio web | pandas.pydata.org | + + +-- + +### Características + +* Dataframes para manipulación de datos con indexación integrada +* Herramientas para importar y exportar datos entre estructuras de datos en memoria y diferentes formatos de archivo +* Gestión integrada de datos en blanco +* Modificación y dinamización de conjuntos de datos + +-- + +### Características (cont.) + +* Subdivisión de grandes conjuntos de datos usando etiquetado e indexación +* Inserción y eliminación de columnas en estructuras de datos +* Agrupación y combinación de conjuntos de datos +* Funcionalidades para trabajo con series de tiempo + +--- + +![](img/jupyter copia.jpg) + +* Herramienta que permite utilizar código, texto, expresiones matemáticas, gráficos, e imágenes +* Interacción vía navegador + +-- + +![](img/jupyter copia.jpg) + +JUlia + PYThon + R = Jupyter + + +-- + +«Los cultores de la programación ilustrada pueden ser considerados ensayistas, cuya preocupación principal es la exposición y la excelencia del estilo. Estos autores, con diccionario en mano, eligen cuidadosamente los nombres de sus variables y explican lo que significa cada una. Se esfuerzan para crear un programa que sea comprensible porque sus conceptos se han introducido en un orden que se aviene mejor al entendimiento humano, usando una mezcla de métodos formales e informales que se refuerzan mutuamente.» + +*Tomado de Donald E. Knuth (2009), Literate Programming. The Computer Journal* + +--- + +![](img/Captura de pantalla de 2017-07-28 12-04-27.png) + +-- + +![](img/Captura de pantalla de 2017-07-28 14-29-02.png) + + +-- + +![](img/Captura de pantalla de 2017-07-28 14-29-29.png) + +-- + +![](img/Captura de pantalla de 2017-07-28 14-29-43.png) + + +-- + +![](img/Captura de pantalla de 2017-07-28 14-29-54.png) + + + diff --git a/translate/qml-1-basics-es.md b/translate/qml-1-basics-es.md new file mode 100644 index 00000000000..3dc92a7e2b3 --- /dev/null +++ b/translate/qml-1-basics-es.md @@ -0,0 +1,968 @@ +![](img/qt_logo_green_rgb.png) +## Visual Programming with QML and Qt Quick + +### Meetup #1: Basics + +-------------- + +###### by Carlos Enrique Pérez Sánchez + +--- + +# Let's get started! + +--- + +## What we are covering? + +- QML + - What's that? + - QML Syntax Basics + - QML Object Attributes + - **Property Binding** + - Signal and Handler Event System + +-- + +- Qt Quick + - What's that? + - Qt Quick 1? Qt Quick 2? + - Visual types in QML + - Responding to User Input in QML + - Animations in QML + - Displaying Text in QML + - Layouts and positioners in QML + - Style and Theme Support + +-- + +- Advanced Application Development Topics + - Best Practices for QML and Qt Quick + - QML Coding Conventions + - Performance Considerations And Suggestions + - Scalable User Interfaces + +--- + +# QML + +-------------- + +### Qt Meta-Object Language + +*Consult "The QML Reference" in Qt Help* + +--- + +## What is QML? +*Consult "QML Applications" in Qt Help* + +QML is a user interface specification and programming language + +-- + +Is a declarative language that allows user interfaces to be described in terms of their visual components and how they interact and relate with one another + +-- + +It allows developers and designers alike to create highly performant, fluidly animated and visually appealing applications + +-- + +QML offers a highly readable, declarative, JSON-like syntax with support for imperative JavaScript expressions combined with dynamic property bindings + +--- + +### What can we do with QML? + +**Building applications for:** +- Desktop devices (Linux, MacOS, Windows) +- Mobile platforms (Android, iOS/tvOS/watchOS, WinRT) +- Embedded platforms (Embedded Linux, INTEGRITY, QNX, VxWorks) + +--- + +### Embedded platforms? + +![](img/qt-for-mcu-diagram.png) + +-- + +#### STM32F769 + +![](img/STM32F769.jpg) + +-- + +#### STM32F746 + +![](img/STM32F746.jpg) + +-- + +#### STM32F469 + +![](img/STM32F469.jpg) + +-- + +[Qt for MCUs (download link)](img/Qt-for-MCUs-Ultimate-Performance-Tiny-Footprint.mkv "Qt for MCUs") + +--- + +## Syntax basics +*Consult "Syntax basics" in Qt Help* + +- Imports +- Object declarations +- Child objects +- Comments + +-- + +```qml +import QtQuick 2.12 +import QtQuick.Controls 2.12 + +/* + Creating an ApplicationWindow is a lot + better than creating just a Window. +*/ + +ApplicationWindow { + id: app + + width: 400 + height: 500 + + color: 'plum' // This is a HTML color +} +``` + +--- + +## QML Object Attributes +*Consult "QML Object Attributes" in Qt Help* + +- The *id* Attribute +- Property Attributes +- Signal Attributes +- Signal Handler Attributes +- Method Attributes +- Enumeration Attributes + +--- + +## Property Binding +*Consult "Property Binding" in Qt Help* + +- Creating bindings +- Removing bindings + +--- + +## Signal and Handler Event System +*Consult "Signal and Handler Event System" in Qt Help* + +- Receiving signals with signal handlers +- Property change signal handlers +- Attached signal handlers +- Adding signals to custom QML types +- Connecting signals to methods and signals + +--- + +## Challenge 1 + +![](img/challenge-1-screenshot.png) + +-- + +```qml +import QtQuick 2.12 +import QtQuick.Controls 2.12 + +ApplicationWindow { + visible: true + width: 640 + height: 480 + title: qsTr("Challenge 1") + + Button { + id: myButton + + property int numberOfClicks: 0 + + anchors.centerIn: parent + text: "Ha dado " + numberOfClicks + " clicks" + + onClicked: { + numberOfClicks++ + } + } +} +``` + +-- + +### Challenge 1.1 + +* Bind the `height` of the button to `40 * (numberOfClicks + 1)` +* Set the `highlighted` property of the button to `true` if the number of clicks is even + +-- + +```qml +import QtQuick 2.12 +import QtQuick.Controls 2.12 + +ApplicationWindow { + visible: true + width: 640 + height: 480 + title: qsTr("Challenge 1.1") + + Button { + id: myButton + + property int numberOfClicks: 0 + + anchors.centerIn: parent + height: 40 * (numberOfClicks + 1) + text: "Ha dado " + numberOfClicks + " clicks" + highlighted: numberOfClicks % 2 === 0 + + onClicked: { + numberOfClicks++ + } + } +} +``` + +--- + +# Qt Quick + +--- + +## What is Qt Quick? +*Consult "QML Applications" in Qt Help* + +Qt Quick is the standard library of types and functionality for QML + +-- + +It includes visual types, interactive types, animations, models and views, particle effects and shader effects. A QML application developer can get access to all of that functionality with a single import statement + +--- + +## Qt Quick 1 vs Qt Quick 2 + +Qt Quick Controls 1 was originally developed to support desktop platforms, with mobile and embedded support coming shortly afterwards + +-- + +They have a very broad scope, in that they provide a styling system flexible enough to allow the development of applications that have either a platform-dependent or platform-independent style + +-- + +On embedded systems, where the hardware has limited resources, this approach can be inefficient. Qt Quick Controls 2 was designed to solve this problem + +--- + +### QML vs C++ + +In many cases, the internal state of a control can be more efficiently processed in C++. For example, handling input events in C++ makes a difference for controls that would otherwise need to create internal `MouseAreas` and attached `Keys` objects + +--- + +### Styles + +Not only does handling events and logic in C++ increase performance, but it allows the visual QML layer to be a simple, declarative layer on top. This is reflected in the structure of the controls project: all visual implementations sit in the imports folder, so that users who want to create their own complete style can copy the folder and start tweaking + +-- + +In Qt Quick Controls 2, styles no longer provide components that are dynamically instantiated by controls, but controls themselves consist of item delegates that can be replaced + +-- + +### Modularity and Simplicity + +In Qt Quick Controls 1: +```qml +ScrollView { + horizontalScrollBarPolicy: Qt.ScrollBarAlwaysOff + Flickable { + // ... + } +} +``` + +In Qt Quick Controls 2: + +```qml +Flickable { + // ... + ScrollBar.vertical: ScrollBar { } +} +``` + +-- + +*The API of Qt Quick Controls 2 aims to be clean and simple. Common operations are easy, and more advanced ones are liberally documented with snippets that can be copied into your code* + +*-- Qt Docs* + +-- + +![](img/QQC1-QQC2-Feature-Comparison.png) + +--- + +## Visual Types in QML +*Consult "Qt Quick", "Qt Quick Controls 2", "Use Case - Visual Elements In QML", "Qt Quick QML Types" and "Qt Quick Controls Examples" in Qt Help* + +--- + +## Responding to User Input in QML +*Consult "Button", "Qt Quick Controls Guidelines" and "First Steps with QML" in Qt Help* + +--- + +## Style and Theme Support +*Consult "Styling Qt Quick Controls 2" and related styles, and "Qt Quick Controls Configuration File" in Qt Help* + +-- + +Qt Quick Controls Configuration File: + +``` +[Controls] +Style=Material + +[Material] +Theme=Light +Accent=Blue +Primary=BlueGray +Foreground=Brown +Background=Grey + +Variant=Dense +``` + +--- + +## Animations in QML +*Consult "Use case - Animations In QML", "Important Concepts in Qt Quick - States, Transitions and Animations" and "Animations and Transitions In Qt Quick" in Qt Help* + +-- + +### Fluid UIs + +Animations are a primary concept in QML + +-- + +QML was designed to facilitate the creation of fluid UIs. These are user interfaces where the UI components animate instead of appearing, disappearing, or jumping abruptly. + +-- + +Qt Quick provides two simple ways to have UI components move with animation instead of instantly appearing at their new location: + +- States and Transitions +- Animating Property Changes (behaviors) + +-- + +* **PropertyAnimation** +* NumberAnimation +* ColorAnimation +* RotationAnimation + +... and more + +-- + +#### States and Transitions + +```qml +Rectangle { + id: button + anchors.centerIn: parent + width: 75; height: 75 + state: "RELEASED" + + MouseArea { + anchors.fill: parent + onPressed: button.state = "PRESSED" + onReleased: button.state = "RELEASED" + } + + states: [ + State { + name: "PRESSED" + PropertyChanges { target: button; color: "blue"} + }, + State { + name: "RELEASED" + PropertyChanges { target: button; color: "#BBBBFF"} + } + ] + + transitions: [ + Transition { + from: "PRESSED" + to: "RELEASED" + ColorAnimation { target: button; duration: 200 } + }, + Transition { + from: "RELEASED" + to: "PRESSED" + ColorAnimation { target: button; duration: 200 } + } + ] +} +``` + +-- + +#### Behavior + +```qml +Rectangle { + id: button + anchors.centerIn: parent + width: 75; height: 75 + color: mouseArea.pressed ? "red" : "yellow" + Behavior on color { ColorAnimation {} } + + MouseArea { + id: mouseArea + anchors.fill: parent + } +} +``` + +-- + +## Challenge 2 + +Animate all changes to the `height` property of the button of the previous challenge + +-- + +#### Applying animations in a sequence and/or in parallel + +```qml +SequentialAnimation { + id: someAnimation + + NumberAnimation { /* ... */ } + PauseAnimation { duration: 1000 } + ColorAnimation { /* ... */ } + // ... +} +``` + +```qml +ParallelAnimation { + id: someAnimation + + NumberAnimation { /* ... */ } + ColorAnimation { /* ... */ } + // ... +} +``` + +-- + +## Challenge 3 + +Design the following UI: + +![](img/challenge-3-screenshot.png) + +-- + +- Square side: `100` +- Square position: `Centered` +- Square color: `"teal"` +- Square border color: `Qt.darker("teal")` +- Square border width: `10` +- Button text: `"Start"` +- Button horizontal position: `Horizontally centered` +- Button vertical position: `Bottom`, `margin=10` +- Style: `Material` +- Material theme: `Light` +- Material accent: `Blue` + +-- + +```qml +import QtQuick 2.12 +import QtQuick.Controls 2.12 + +ApplicationWindow { + id: applicationWindow + visible: true + width: 640 + height: 480 + title: qsTr("Challenge 3") + + Rectangle { + id: square + + anchors.centerIn: parent + width: 100 + height: width + color: "teal" + border { color: Qt.darker("teal"); width: 10 } + } + + Button { + id: button + + anchors { horizontalCenter: parent.horizontalCenter; bottom: parent.bottom; bottomMargin: 10 } + + text: "Start" + highlighted: true + } +} +``` + +-- + +Make the button smoothly ascend and disappear (at the same time) in 0.5 seconds when clicked + +-- + +This can be done by adding the following lines to the button's code: + + +```qml +onClicked: { + buttonAnimation.start() +} + +ParallelAnimation { + id: buttonAnimation + + NumberAnimation { target: button; property: "anchors.bottomMargin"; to: 30; duration: 500 } + NumberAnimation { target: button; property: "opacity"; to: 0.0; duration: 500 } +} +``` + +-- + +Make the square grow to 200 pixels of side and then back to 100, repeatedly. All every second, after the button is clicked. + +-- + +This can be done by adding the following code to the square's code: + +```qml +SequentialAnimation { + id: animation + + loops: Animation.Infinite + + NumberAnimation { target: square; property: "width"; to: 200; duration: 500 } + NumberAnimation { target: square; property: "width"; to: 100; duration: 500 } +} +``` + +or... + +```qml +SequentialAnimation on width { + id: animation + + loops: Animation.Infinite + running: false // necessary when applying over a property ("on width") to make it not running from the beginning + + NumberAnimation { to: 200; duration: 500 } + NumberAnimation { to: 100; duration: 500 } +} +``` + +-- + +And adding the following function to the square to run the animation: + +```qml +function runAnimation() { + animation.start() +} +``` + +And calling it when the button is clicked (in the button's code): + +```qml +onClicked: { + square.runAnimation() + buttonAnimation.start() +} +``` + +-- + +Make the button rotate 360º over itself every second, indefinitely. + +-- + +This can be done by enclosing the square animation into a `ParallelAnimation`: + +```qml +ParallelAnimation { + id: animation + + RotationAnimation { target: square; to: from + 360; duration: 1000; loops: Animation.Infinite } + + SequentialAnimation { + loops: Animation.Infinite + + NumberAnimation { target: square; property: "width"; to: 200; duration: 500 } + NumberAnimation { target: square; property: "width"; to: 100; duration: 500 } + } +} +``` + +-- + +Create two new components: `Square` and `AnimatedButton` and put the respective objects there. + +--- + +## Displaying Text in QML +*Consult "Text", "Use Case - Displaying Text In QML" and "Supported HTML Subset" in Qt Help* + +- Text properties +- HTML + +-- + +```qml +Text { + text: "Hello World!" + color: "#9C27B0" + font { pointSize: 24; bold: true; italic: true } +} +``` + +```qml +Text { + text: "Hello World!" +} +``` + +--- + +## Layouts and positioners in QML +*Consult "Use Case - Positioners and Layouts In QML" and all the links provided in that page in Qt Help* + +- Manual Positioning +- Anchors +- Layouts + +-- + +### Anchors + +![](img/anchors-positioning.png) + +-- + +### Layouts + +```qml +import QtQuick 2.12 +import QtQuick.Controls 2.12 + +ApplicationWindow { + RowLayout { + anchors.fill: parent + spacing: 6 + Rectangle { + color: 'azure' + Layout.preferredWidth: 100 + Layout.preferredHeight: 150 + } + Rectangle { + color: "plum" + Layout.fillWidth: true + Layout.fillHeight: true + } + } +} +``` + +--- + +# Advanced Application Development Topics +*Consult "Best Practice Guides" in Qt Help* + +--- + +## Best Practices for QML and Qt Quick +*Consult "Best Practices for QML and Qt Quick" in Qt Help* + +--- + +### QML Coding Conventions +*Consult "QML Coding Conventions" in Qt Help* + +-- + +#### QML Object Declarations +Throughout our documentation and examples, QML object attributes are always structured in the following order: + +- id +- property declarations +- signal declarations +- JavaScript functions +- object properties +- child objects +- states +- transitions + +For better readability, we separate these different parts with an empty line. + +--- + +#### Grouped Properties + +If using multiple properties from a group of properties, consider using group notation instead of dot notation if it improves readability + +-- + +For example, this: + +```qml +Rectangle { + anchors.left: parent.left + anchors.top: parent.top + anchors.right: parent.right + anchors.leftMargin: 20 +} +``` + +could be written like this: + +```qml +Rectangle { + anchors { + left: parent.left + top: parent.top + right: parent.right + leftMargin: 20 + } +} +``` + +--- + +#### Lists + +If a list contains only one element, we generally omit the square brackets + +-- + +For example, it is very common for a component to only have one state. In this case, instead of + +```qml +states: [ + State { + name: "open" + PropertyChanges { target: container; width: 200 } + } +] +``` + +We will write this: + +```qml +states: State { + name: "open" + PropertyChanges { target: container; width: 200 } +} +``` + +--- + +#### JavaScript Code + +If the script is a single expression, we recommend writing it inline: + +```qml +Rectangle { color: "blue"; width: parent.width / 3 } +``` + +-- + +If the script is only a couple of lines long, we generally use a block: + +```qml +Rectangle { + color: "blue" + width: { + var w = parent.width / 3 + console.debug(w) + return w + } +} +``` + +-- + +If the script is more than a couple of lines long or can be used by different objects, we recommend creating a function and calling it like this: + +```qml +function calculateWidth(object) +{ + var w = object.width / 3 + // ... + // more javascript code + // ... + console.debug(w) + return w +} + +Rectangle { color: "blue"; width: calculateWidth(parent) } +``` + +-- + +For long scripts, we will put the functions in their own JavaScript file and import it like this: + +```qml +import "myscript.js" as Script + +Rectangle { color: "blue"; width: Script.calculateWidth(parent) } + +``` + +--- + +### Performance Considerations And Suggestions +*Consult "Performance Considerations And Suggestions" in Qt Help* + +QML is more or less an interpreted programming language. This will radically change in Qt 6, as we want to make the QML core based on C++ instead of JavaScript + +-- + +Currently, as Qt 5 uses a JavaScript backend for QML, there are some performance considerations that developers must take in account, mainly when targeting low-power devices such as mobile or embedded systems + +--- + +#### Timing Considerations + +As an application developer, you must strive to allow the rendering engine to achieve a consistent 60 frames-per-second refresh rate. 60 FPS means that there is approximately 16 milliseconds between each frame in which processing can be done, which includes the processing required to upload the draw primitives to the graphics hardware + +-- + +In practice, this means that the application developer should: +- use asynchronous, event-driven programming wherever possible +- use worker threads to do significant processing +- never manually spin the event loop +- never spend more than a couple of milliseconds per frame within blocking functions + +Failure to do so will result in skipped frames, which has a drastic effect on the user experience. + +-- + +**Note**: A pattern which is tempting, but should *never* be used, is creating your own `QEventLoop` or calling `QCoreApplication::processEvents()` in order to avoid blocking within a C++ code block invoked from QML. This is dangerous, because when an event loop is entered in a signal handler or binding, the QML engine continues to run other bindings, animations, transitions, etc. Those bindings can then cause side effects which, for example, destroy the hierarchy containing your event loop. + +--- + +#### JavaScript Code + +Most QML applications will have a large amount of JavaScript code in them, in the form of dynamic functions, signal handlers, and property binding expressions + +-- + +Due to the deep link between QML and JavaScript, loading a JS function can be faster than loading a C++ method. However, executing JS code is many times slower than executing C++ code. You should not use JS for long-time processing, use C++ instead. + +-- + +Things to avoid in binding expressions to maximize optimizability: +- declaring intermediate JavaScript variables +- accessing "var" properties +- calling JavaScript functions +- constructing closures or defining functions within the binding expression +- accessing properties outside of the immediate evaluation scope +- writing to other properties as side effects + +--- + +#### Common UI elements + +- **Text:** + - Use the `PlainText` format instead of `StyledText` wherever possible, setting it explicitly + - Use only `StyledText` only if you want to use HTML tags + - You should only use AutoText if the text might be (but probably isn't) `StyledText` as this mode will incur a parsing cost + +-- + +- **Images:** + - Use `asynchronous` loading on large images + - Set an explicit `sourceSize` to keep in memory a smaller image + - Avoid smoothing images by enabling `image.smooth` only if the size of the image is not equal to its `sourceSize` + - Avoid run-time composition by providing the pre-composed image resource with your application (for example, providing elements with shadow effects) + +--- + +#### Animations + +Avoid running JavaScript during animation. For example, running a complex JavaScript expression for each frame of an `x` property animation should be avoided. Developers should be especially careful using script animations, as these are run in the main thread (and therefore can cause frames to be skipped if they take too long to complete). + +-- + +*Consult "Performance Considerations And Suggestions" in Qt Help* + +--- + +### Scalable User Interfaces +*Consult "Scalability", "High DPI Displays" and "High-DPI Support in Qt Quick Controls 2" in Qt Help* + +**Warning:** Qt Quick Controls 1 are not compatible with Qt's automatic high-DPI scaling. There is currently no available solution for high-DPI support in applications wishing to mix Qt Quick Controls 1 and Qt Quick Controls 2. + +-- + +- **Text:** + - Use `font.pointSize` instead of `font.pixelSize` + +- **Images and Icons:** + - Use SVG for icons and small images + +--- + +## Challenge + +#### A Timer: +![](img/challenge-4-home-screenshot.png) + +-- + +* Set the minutes and seconds in the `SpinBox` +* Click the *START* button to begin the countdown using a `Timer` +* Show the remaining time in the upper `Label` +* The text of the button must be *STOP* while the timer is running or the alarm is active +* When the timeout comes, activate the alarm by animating the color of the window from "red" to "white" every 1s until the user clicks *STOP* to bring the application to the initial state + +--- + +## Upcoming events + +* Integrating QML with a backend language + - C++ + - Python + - Go (no officially supported) +* Model/View Programming with QML + - Model + - Delegates + +--- + +# Wrapping up + +Thank you for coming! \ No newline at end of file diff --git a/translate/qml-2-backend-es.md b/translate/qml-2-backend-es.md new file mode 100644 index 00000000000..fe147b6bbec --- /dev/null +++ b/translate/qml-2-backend-es.md @@ -0,0 +1,973 @@ +![](img/qt_logo_green_rgb.png) +## Visual Programming with QML and Qt Quick + +### Meetup #2: Integrating QML with a backend language + +-------------- + +###### by Carlos Enrique Pérez Sánchez + +--- + +# Let's get started! + +--- + +## What we are covering? + +- The Qt Meta-Object System + - MOC vs Templates + - Performance implications +- Integrating QML and JavaScript +- Integrating QML and C++ +- Integrating QML and Python + +--- + +# The Qt Meta-Object System + +*Consult "The Meta-Object System", "Why Does Qt Use MOC for Signals and Slots?" in Qt Help* + +-- + +Qt's meta-object system provides the signals and slots mechanism for inter-object communication, run-time type information, and the dynamic property system + +-- + +The meta-object system is based on three things: +1. The `QObject` class +2. The `Q_OBJECT` macro +3. The Meta-Object Compiler - `moc` + +--- + +## MOC vs Templates + +**Pros of using templates against MOC** +* Allows the compiler to generate code on the fly +* Are very fast + +**Cons of using templates against MOC** +* code size +* readability +* usability +* extensability +* robustness +* ultimately design beauty + +-- + +### Performance implications + +* Emmiting a signal is approximately the cost of **four** ordinary function calls with common template implementations +* Qt requires effort comparable to about **ten** function calls + +-- + +### Why? + +Qt's signals & slots mechanism includes: +* A generic marshaller +* Introspection +* Queued calls between different threads +* Unmatched **runtime safety** + +-- + +## Calling performance is not everything + +--- + +# Integrating QML and JavaScript + +*Consult "Integrating QML and JavaScript", "Use Case - Integrating JavaScript in QML" in Qt Help* + +-- + +The QML language uses a JSON-like syntax and allows various expressions and methods to be defined as JavaScript functions. +It also allows users to import JavaScript files and use the functionality those imports provide. + +-- + +## JavaScript Expressions + +- Signals handlers + +```qml +Button { + id: myButton + + onClicked: { + // ... + } +} +``` + +-- + +- Functions + +```qml +function foo(x, y) { + // ... +} +``` + +-- + +- Property bindings + +```qml +height: 100 + +height: parent.height / 2 + +height: Math.min(parent.width, parent.height) + +height: parent.height > 100 ? parent.height : parent.height/2 + +height: { + if (parent.height > 100) + return parent.height + else + return parent.height/2 +} + +height: someMethodThatReturnsHeight() +``` + +-- + +- JS resources + +```qml +// MyButton.qml +import QtQuick 2.0 +import "my_button_impl.js" as Logic + +Rectangle { + id: rect + width: 200 + height: 100 + + MouseArea { + id: mouseArea + anchors.fill: parent + onClicked: Logic.onClicked(rect) + } +} +``` + +--- + +# Integrating QML and C++ + +-- + +![](img/Person-Material-Light.png) +![](img/Person-Material-Dark.png) + +![](img/Person-Universal-Light.png) +![](img/Person-Default.png) + +-- + +*person.h* + +```c++ +#ifndef PERSON_H +#define PERSON_H + +#include +#include +#include +#include + +class Person : public QObject +{ + Q_OBJECT + + Q_PROPERTY(QString name READ getName WRITE setName NOTIFY nameChanged) + Q_PROPERTY(bool isMale READ getIsMale WRITE setIsMale NOTIFY isMaleChanged) + Q_PROPERTY(QString imagePath READ getImagePath WRITE setImagePath NOTIFY imagePathChanged) + +public: + explicit Person(QObject *parent = nullptr); + + QString getName() const; + void setName(const QString &value); + + bool getIsMale() const; + void setIsMale(bool value); + + QString getImagePath() const; + void setImagePath(const QString &value); + +signals: + void nameChanged(const QString &value); + void isMaleChanged(bool value); + void imagePathChanged(const QString &value); + +public slots: + QString selectImage(); + bool save(); + bool load(); + +private: + QString name; + bool isMale = true; + QString imagePath; +}; + +#endif // PERSON_H +``` + +-- + +*person.cpp* + +```c++ +#include "person.h" + +Person::Person(QObject *parent) : QObject(parent) +{ + +} + +QString Person::getName() const +{ + return name; +} + +void Person::setName(const QString &value) +{ + if (name != value) { + name = value; + emit nameChanged(value); + } +} + +bool Person::getIsMale() const +{ + return isMale; +} + +void Person::setIsMale(bool value) +{ + if (isMale != value) { + isMale = value; + emit isMaleChanged(value); + } +} + +QString Person::getImagePath() const +{ + return imagePath; +} + +void Person::setImagePath(const QString &value) +{ + if (imagePath != value) { + imagePath = value; + emit imagePathChanged(value); + } +} + +QString Person::selectImage() +{ + QString path = QFileDialog::getOpenFileName(); + if (!path.isEmpty()) { + setImagePath(path); + } + + return path; +} + +bool Person::save() +{ + QString path = QFileDialog::getSaveFileName(); + if (!path.isEmpty()) { + QFile f(path); + if (!f.open(QFile::WriteOnly)) { + return false; + } + + QDataStream out(&f); + out << name << isMale << imagePath; + f.close(); + return true; + } + return false; +} + +bool Person::load() +{ + QString path = QFileDialog::getOpenFileName(); + if (!path.isEmpty()) { + QFile f(path); + if (!f.open(QFile::ReadOnly)) { + return false; + } + + QDataStream in(&f); + QString tempName; + bool tempIsMale; + QString tempImagePath; + in >> tempName >> tempIsMale >> tempImagePath; + setName(tempName); + setIsMale(tempIsMale); + setImagePath(tempImagePath); + f.close(); + return true; + } + return false; +} +``` + +-- + +*main.cpp* + +```c++ +#include +#include + +#include "Person/person.h" + +int main(int argc, char *argv[]) +{ + QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + + QApplication app(argc, argv); + app.setOrganizationName("Cubantech"); + app.setApplicationName("Person"); + app.setApplicationVersion("1.0"); + + qmlRegisterType("Backend", 1, 0, "Person"); + + QQmlApplicationEngine engine; + const QUrl url(QStringLiteral("qrc:/main.qml")); + QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, + &app, [url](QObject *obj, const QUrl &objUrl) { + if (!obj && url == objUrl) + QCoreApplication::exit(-1); + }, Qt::QueuedConnection); + engine.load(url); + + return app.exec(); +} + +``` + +-- + +*main.qml* + +```qml +import QtQuick 2.13 +import QtQuick.Controls 2.13 +import QtQuick.Layouts 1.13 + +import Backend 1.0 + +ApplicationWindow { + id: applicationWindow + + visible: true + width: 340 + height: 200 + title: Qt.application.name + ' - v' + Qt.application.version + + Person { + id: person + + name: textFieldName.text + isMale: radioButtonMale.checked + } + + Image { + id: image + + width: 100 + height: 100 + anchors.left: parent.left + anchors.leftMargin: 16 + anchors.top: parent.top + anchors.topMargin: 16 + source: person.imagePath ? ("file:///" + person.imagePath) : "" + fillMode: Image.PreserveAspectFit + } + + Button { + id: buttonSelectImage + + text: qsTr("Select") + anchors.top: image.bottom + anchors.topMargin: 10 + anchors.right: image.right + anchors.rightMargin: 0 + anchors.left: image.left + anchors.leftMargin: 0 + + onClicked: { + person.selectImage() + } + } // Button (select image) + + TextField { + id: textFieldName + + text: qsTr("") + anchors.top: parent.top + anchors.topMargin: 10 + anchors.right: parent.right + anchors.rightMargin: 10 + anchors.left: image.right + anchors.leftMargin: 10 + placeholderText: "Name" + focus: true + } + + RowLayout { + id: rowLayout + + anchors.left: textFieldName.left + anchors.leftMargin: 0 + anchors.top: textFieldName.bottom + anchors.topMargin: 10 + + RadioButton { + id: radioButtonMale + text: qsTr("Male") + checked: true + } + + RadioButton { + id: radioButtonFemale + text: qsTr("Female") + } + } // RowLayout + + Button { + id: buttonSave + + text: qsTr("Save") + anchors.left: buttonLoad.right + anchors.leftMargin: 10 + anchors.top: buttonLoad.top + anchors.right: parent.right + anchors.rightMargin: 10 + highlighted: true + + onClicked: { + person.save() + } + } // Button (save) + + Button { + id: buttonLoad + + text: qsTr("Load") + anchors.left: textFieldName.left + anchors.leftMargin: 0 + anchors.top: buttonSelectImage.top + anchors.topMargin: 0 + + onClicked: { + if (person.load()) { + textFieldName.text = person.name + if (person.isMale) { + radioButtonMale.checked = true + } else { + radioButtonFemale.checked = true + } + } + } + } // Button (load) +} +``` + +-- + +qtquickcontrols2.conf + +```ini +; This file can be edited to change the style of the application +; Read "Qt Quick Controls 2 Configuration File" for details: +; http://doc.qt.io/qt-5/qtquickcontrols2-configuration.html + +[Controls] +Style=Material + +[Material] +Accent=Green +Variant=Dense +; Theme=Dark + +[Universal] +Accent=Green +; Theme=Dark + +``` + +--- + +### Challenge 1 + +***A simple text editor*** +- Open file +- Save file +- Customize theme + +![](img/Example1.png) + +-- + +*filemanager.h* + +```c++ +#ifndef FILEMANAGER_H +#define FILEMANAGER_H + +#include +// File dialogs are widget-based. If you add `Qt += widgets` to your .pro file you can just #include +#include +#include +#include + +class FileManager : public QObject +{ + Q_OBJECT +public: + explicit FileManager(QObject *parent = nullptr); + +signals: + +public slots: + QString open(); + bool saveAs(const QString &textToSave); +}; + +#endif // FILEMANAGER_H +``` + +-- + +*filemanager.cpp* + +```c++ +#include "filemanager.h" + +FileManager::FileManager(QObject *parent) : QObject(parent) +{ + // Initialization function +} + +QString FileManager::open() +{ + QString path = QFileDialog::getOpenFileName(); // show a dialog to peek a file + if (!path.isEmpty()) { // if the path is not empty (i.e. the user do not rejected the dialog) + QFile f(path); // initialize a file with the selected path + if (f.open(QFile::ReadOnly)) { // open the file for reading, return true on success, false otherwise + QTextStream in(&f); // create a stream of text pointing to the file above + QString content = in.readAll(); // read the whole file as a text stream + f.close(); // close the file + return content; // return the content + } + } + + return QString(); // return an empty string if something fails +} + +bool FileManager::saveAs(const QString &textToSave) +{ + bool ok = false; + QString path = QFileDialog::getSaveFileName(); // show a dialog to save a file + if (!path.isEmpty()) { // if the path is not empty (i.e. the user do not rejected the dialog) + QFile f(path); // initialize a file with the selected path + if (f.open(QFile::WriteOnly)) { // open the file for writing, return true on success, false otherwise + QTextStream out(&f); // create a stream of text pointing to the file above + out << textToSave; // write the whole text as a text stream to the file + ok = true; // all is OK, update the result + f.close(); // close the file + } + } + + return ok; // return a result +} +``` + +-- + +*main.cpp* + +```c++ +// QGuiApplication requires less initialization, but you must must include +// QApplication if you want to show widget-based controls like QFileDialog. +#include +#include + +// Include the C++ classes you want to expose to QML +#include "src/core/FileManager/filemanager.h" + +int main(int argc, char *argv[]) +{ + // Enable High DPI Scaling + QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + + QApplication app(argc, argv); // Create a QApplication with the parameters pased + // The following is required to manage configuration files with QSettings and Settings + app.setOrganizationName("Cubantech"); // Set the name of your organization + app.setApplicationName("Example 1"); // Set the name of your application + app.setApplicationVersion("1.0"); // Set the version of the application + + // Register C++ types to QML + qmlRegisterType("Example", 1, 0, "FileManager"); + + QQmlApplicationEngine engine; // Create the QML engine + const QUrl url(QStringLiteral("qrc:/qml/ui/main.qml")); // URL of the root QML component (must be an ApplicationWindow or Window) + // Check errors after object creation + QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, + &app, [url](QObject *obj, const QUrl &objUrl) { + if (!obj && url == objUrl) + QCoreApplication::exit(-1); + }, Qt::QueuedConnection); + engine.load(url); // Load the selected root component + + return app.exec(); // Enter the event loop and exit the application when it ends, returning its error code +} +``` + +-- + +*main.qml* + +```qml +import QtQuick 2.13 +import QtQuick.Controls 2.13 +import QtQuick.Controls.Material 2.13 + +// Qt Labs imports +import Qt.labs.settings 1.0 + + +// Import C++ types +import Example 1.0 + +// Import local QML types +import "Dialogs" + +ApplicationWindow { + id: applicationWindow + + title: Qt.application.name + ' - v' + Qt.application.version + visible: true + width: 600 + height: 500 + Material.accent: Material.Blue + + function loadUiSettings() { + applicationWindow.Material.theme = ~~settings.value("ui/theme", Material.Light) + } + + Component.onCompleted: { + loadUiSettings() + } + + menuBar: ApplicationMenuBar { } + + ScrollView { + + anchors.margins: 10 + anchors.fill: parent + clip: true + + TextArea { + id: textArea + + focus: true + selectByMouse: true + } + } + + FileManager { + id: fileManager + } + + MessageDialog { + id: messageDialog + + anchors.centerIn: Overlay.overlay + width: applicationWindow.width > 300 ? 300 - 40 : applicationWindow.width - 40 + height: applicationWindow.height > 250 ? 250 - 40 : applicationWindow.height - 40 + modal: true + title: "Message" + } + + Settings { + id: settings + } +} +``` + +-- + +*ApplicationMenuBar.qml* + +```qml +import QtQuick 2.13 +import QtQuick.Controls 2.13 +import QtQuick.Controls.Material 2.13 + +MenuBar { + Menu { + title: "File" + + MenuItem { + text: "Open" + onTriggered: { + textArea.text = fileManager.open() + } + } + + MenuItem { + text: "Save as..." + onTriggered: { + var result = fileManager.saveAs(textArea.text) + messageDialog.message = result ? "Saved" : "Error" + messageDialog.open() + } + } + MenuItem { text: "Close"; onTriggered: Qt.quit() } + } // Menu (File) + + Menu { + title: "Theme" + + MenuItem { + text: "Material Light" + enabled: Material.theme !== Material.Light + + onTriggered: { + applicationWindow.Material.theme = Material.Light + settings.setValue("ui/theme", Material.Light) + } + } + MenuItem { + text: "Material Dark" + enabled: Material.theme !== Material.Dark + + onTriggered: { + applicationWindow.Material.theme = Material.Dark + settings.setValue("ui/theme", Material.Dark) + } + } + } // Menu (theme) +} +``` + +-- + +*MessageDialog.qml* + +```qml +import QtQuick 2.13 +import QtQuick.Controls 2.13 + +Dialog { + id: messageDialog + + property alias message: labelMessage.text + + standardButtons: Dialog.Ok + + Label { + id: labelMessage + + anchors.fill: parent + wrapMode: Text.Wrap + } +} +``` + +--- + +# Integrating QML and Python + +-- + +## Qt for Python (PySide2) + +![](img/pyside2.png) + +-- + +*The **Qt for Python** project aims to provide a complete port of the PySide module to Qt 5. The development started on GitHub in May 2015. The project managed to port PySide to Qt 5.3, 5.4 & Qt 5.5.* + +-- + +*The **PySide2** module was released mid June 2018 as a Technical Preview (supporting Qt 5.11), and it has been fully supported since Qt 5.12.* + +-- + +* **Qt for Python** is available under LGPLv3/GPLv2 and commercial license for the following platforms* + +  | Linux | | macOS | | Windows |   +---------- | ------ | ------ | ------ | ------ | ------- | ------ + | x86 | x64 | x86 | x64 | x86 | x64 +Python 2.7 | No* | Yes | No* | Yes | No** | No** +Python 3.5 | No* | Yes | No* | Yes | Yes | Yes + + * No Qt release + + ** MSVC issue with Python 2.7 and Qt + +--- + +* Install python: + +```bash +$ sudo apt install python3 +``` + +* Install PySide2 + +```bash +$ pip3 install pyside2 +``` + +--- + +### Challenge 2 (again) + +***A simple text editor*** +- Open file +- Save file +- Customize theme + +![](img/Example1.png) + +-- + +*filemanager.py* + +```python +# This Python file uses the following encoding: utf-8 +from PySide2.QtCore import QObject, QFile, QTextStream, Slot +from PySide2.QtWidgets import QFileDialog + +class FileManager(QObject): + # Initialization function + def __init__(self, parent = None): + QObject.__init__(self, parent) + + # if the slot returns something, its type must be explicitly set in the decorator + @Slot(result=str) + def open(self): + path = QFileDialog.getOpenFileName()[0] # show a dialog to peek a file + if path != str(): # if the path is not empty (i.e. the user do not rejected the dialog) + f = QFile(path) # initialize a file with the selected path + opened = f.open(QFile.ReadOnly) # open the file for reading, return True on success, False otherwise + if opened: + stream = QTextStream(f) # create a stream of text pointing to the file above + content = stream.readAll() # read the whole file as a text stream + f.close() # close the file + return content # return the content + return str() # return an empty string if something fails + + # if the slot returns something, its type must be explicitly set in the decorator + @Slot(str, result=bool) + def saveAs(self, text): + ok = False # to check for errors, default to False (i.e. errors found) + path = QFileDialog.getSaveFileName()[0] # show a dialog to save a file + if path != str(): # if the path is not empty (i.e. the user do not rejected the dialog) + f = QFile(path) # initialize a file with the selected path + opened = f.open(QFile.WriteOnly) # open the file for writing, return True on success, False otherwise + if opened: + stream = QTextStream(f) # create a stream of text pointing to the file above + stream << text # write the whole text as a text stream to the file + ok = True # all is OK, update the result + f.close() # close the file + return ok # return a result + +``` + +-- + +*main.py* + +```python +# This Python file uses the following encoding: utf-8 + +# Python imports +import sys +from os.path import dirname, join + +# Modify the sys.path environment variable +current_dir = dirname(__file__) +src_dir = join(current_dir, "src") +core_dir = join(src_dir, "core") +qml_dir = join(src_dir, "qml") +ui_dir = join(qml_dir, "ui") + +sys.path.append(core_dir) +sys.path.append(qml_dir) + +# PySide2 imports +from PySide2.QtWidgets import QApplication +from PySide2.QtQml import QQmlApplicationEngine +from PySide2.QtCore import QUrl, Qt, QCoreApplication +from PySide2.QtQml import qmlRegisterType + +# Import compiled resource files +import qml_rc # QML files +import qt_rc # Qt Quick Controls 2 Configuration File + +# Import Python types to expose to QML +from FileManager import FileManager + +# Function to check errors in the QML engine after object creation +def checkQmlObjectsCreation(obj, objUrl): + if not obj and objUrl == url: + QApplication.exit(-1) + +# main function, the entry point +if __name__ == "__main__": + # Enable High DPI Scaling + QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling) + + app = QApplication(sys.argv) # Create a QApplication with the parameters pased + # The following is required to manage configuration files with QSettings and Settings + app.setOrganizationName("Cubantech") # Set the name of your organization + app.setApplicationName("Example 1") # Set the name of the application + app.setApplicationVersion("0.1") # Set the version of the application + + # Register Python types to QML + qmlRegisterType(FileManager, 'Example', 1, 0, 'FileManager'); + + engine = QQmlApplicationEngine() # Create the QML engine + url = QUrl("qrc:/qml/ui/main.qml") # URL of the root QML component (must be an ApplicationWindow or Window) + engine.objectCreated.connect(checkQmlObjectsCreation, Qt.QueuedConnection) # Check errors after object creation + engine.load(url) # Load the selected root component + + sys.exit(app.exec_()) # Enter the event loop and exit the application when it ends, returning its error code +``` + +-- + +The QML files are **the same** of the ones used in the C++ example (challenge 1) + +--- + +## Upcoming events + +* Model/View Programming with QML + - Model + - Delegates +* Technical vision for **Qt 6** + +--- + +# Wrapping up + +Thank you for coming! \ No newline at end of file diff --git a/translate/qml-3-models-es.md b/translate/qml-3-models-es.md new file mode 100644 index 00000000000..cec64114729 --- /dev/null +++ b/translate/qml-3-models-es.md @@ -0,0 +1,407 @@ +![](img/qt_logo_green_rgb.png) +## Visual Programming with QML and Qt Quick + +### Meetup #3: Models and views + +-------------- + +###### by Carlos Enrique Pérez Sánchez + +--- + +# Let's get started! + +--- + +## What we are covering? + +- Model/View programming + - The Model/View architecture + - Models + - Delegates + - Using a QML model + - Using a backend model +- Technical vision for Qt 6 + +--- + +# Model/View programming + +*Consult "Model/View Programming" in Qt Help* + +-- + +Qt contains a set of item view classes that use a model/view architecture to manage the relationship between data and the way it is presented to the user + +--- + +## The Model/View architecture + +Model-View-Controller (MVC) is a design pattern originating from Smalltalk that is often used when building user interfaces + +-- + +**In *Design Patterns*, the author writes:** + +*"MVC consists of three kinds of objects. The Model is the application object, the View is its screen presentation, and the Controller defines the way the user interface reacts to user input. Before MVC, user interface designs tended to lump these objects together. MVC decouples them to increase flexibility and reuse."* + +-- + +If the view and the controller objects are **combined**, the result is the **model/view** architecture. This still separates the way that data is stored from the way that it is presented to the user, but provides a simpler framework based on the same principles. This separation makes it possible to display the same data in several different views, and to implement new types of views, without changing the underlying data structures. + +-- + +To allow flexible handling of user input, we introduce the concept of the **delegate**. The advantage of having a delegate in this framework is that it allows the way items of data are rendered and edited to be customized. + +-- + +![](img/modelview.png) + +* The **model** communicates with a source of data, providing an interface for the other components in the architecture. +* The **view** obtains model indexes from the model; these are references to items of data. +* The **delegate** dictates how the data should appear in the view. + +-- + +**Some models...** + +![](img/modelview-models.png) + +-- + +Generally, the model/view classes can be separated into the three groups described above: **models**, **views**, and **delegates**. Each of these components is defined by abstract classes that provide common interfaces and, in some cases, default implementations of features. + +-- + +Models, views, and delegates communicate with each other using signals and slots: + +* Signals from the model inform the view about changes to the data held by the data source. +* Signals from the view provide information about the user's interaction with the items being displayed. +* Signals from the delegate are used during editing to tell the model and view about the state of the editor. + +--- + +## Models + +*Consult "Models and Views in Qt Quick" and "Using C++ Models with Qt Quick Views" in Qt Help* + +--- + +### QML models + +* Integers as models: + +```qml +Item { + width: 200; height: 250 + + ListView { + anchors.fill: parent + model: 5 + delegate: Text { text: "I am item number: " + index } + } +} +``` + +**Note**: The limit on the number of items in an integer model is 100,000,000. + +-- + +* List Model + +```qml +ListModel { + id: fruitModel + + ListElement { + name: "Apple" + cost: 2.45 + } + ListElement { + name: "Orange" + cost: 3.25 + } + ListElement { + name: "Banana" + cost: 1.95 + } +} +``` + +-- + +The above model has two roles, `name` and `cost`. These can be bound to by a `ListView` delegate, for example: + +```qml +ListView { + anchors.fill: parent + model: fruitModel + delegate: Row { + Text { text: "Fruit: " + name } + Text { text: "Cost: $" + cost } + } +} +``` + +-- + +* Object Model + +`ObjectModel` contains the visual items to be used in a view. When an `ObjectModel` is used in a view, the view does not require a delegate because the `ObjectModel` already contains the visual delegate (items). + +-- + +The example below places three colored rectangles in a ListView: + +```qml +import QtQuick 2.0 +import QtQml.Models 2.1 + +Rectangle { + + ObjectModel { + id: itemModel + Rectangle { height: 30; width: 80; color: "red" } + Rectangle { height: 30; width: 80; color: "green" } + Rectangle { height: 30; width: 80; color: "blue" } + } + + ListView { + anchors.fill: parent + model: itemModel + } +} +``` + +--- + +### Simple C++ models + +`QStringList` + +*A model may be a simple QStringList, which provides the contents of the list via the `modelData` role.* + +```c++ +QStringList dataList; +dataList.append("Item 1"); +dataList.append("Item 2"); +dataList.append("Item 3"); +dataList.append("Item 4"); +``` + +-- + +`QVariantList` + +*A model may be a simple `QVariantList`, which provides the contents of the list via the `modelData` role.* + +**Note**: The API works just like with `QStringList`, as shown in the previous section. + +-- + +`QObjectList` + +A list of `QObject*` values can also be used as a model. A `QList` provides the properties of the objects in the list as roles: + +The following application creates a `DataObject` class with `Q_PROPERTY` values that will be accessible as named roles when a `QList` is exposed to QML: + +```c++ +class DataObject : public QObject +{ + Q_OBJECT + + Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) + Q_PROPERTY(QString color READ color WRITE setColor NOTIFY colorChanged) + // ... +}; +``` + +-- + +The `QObject*` is available as the `modelData` property. As a convenience, the properties of the object are also made available directly in the delegate's context. The following code snippet references the `DataModel` properties in the `ListView`'s delegate: + +```qml +ListView { + width: 100; height: 100 + + model: myModel + delegate: Rectangle { + height: 25 + width: 100 + color: model.modelData.color + Text { text: name } + } +} +``` + +-- + +**Pros**: +- Simple implementation + +**Cons**: +- Very inefficient + +------------------------- + +*Why it is inefficient?* + +There is no way for the view to know that the contents of a `QStringList`, `QVariantList`, or `QObjectList` have changed. If it changes, it will be necessary to **reset** the model. + +--- + +### QAbstractItemModel subclass + +*A model can be defined by subclassing `QAbstractItemModel`. This is the best approach if you have a more complex model that cannot be supported by the other approaches* + +*A `QAbstractItemModel` can also automatically notify a QML view when the model data changes.* + +The roles of a `QAbstractItemModel` subclass can be exposed to QML by reimplementing `QAbstractItemModel::roleNames()` + +-- + +Here is an application with a `QAbstractListModel` subclass named `AnimalModel`, which exposes the type and sizes roles. It reimplements `QAbstractItemModel::roleNames()` to expose the role names, so that they can be accessed via QML: + +```c++ +class Animal +{ +public: + Animal(const QString &type, const QString &size); + // ... +}; + +class AnimalModel : public QAbstractListModel +{ + Q_OBJECT +public: + enum AnimalRoles { + TypeRole = Qt::UserRole + 1, + SizeRole + }; + Q_ENUM(AnimalRoles) // exposes the enum to QML + + AnimalModel(QObject *parent = nullptr); + // ... +}; + +QHash AnimalModel::roleNames() const +{ + return { {TypeRole, "type"}, {SizeRole, "size"} }; // C++11 feature +} + +//... + +``` + +-- + +This model is displayed by a `ListView` delegate that accesses the `type` and `size` roles: + +```qml +ListView { + width: 200; height: 250 + + model: myModel + delegate: Text { text: "Animal: " + type + ", " + size } +} +``` + +**QML views are automatically updated when the model changes.** + +--- + +## About delegates + +* The **delegate** dictates how the data should appear in the view. +* In most cases the delegate is able to access the model's roles directly. +* They are recycled + - When a delegates comes out of the view port, it is recycled to build the next delegate that enters + +**That means that delegates cannot store states** + +--- + +# Technical vision for Qt 6 + +-- + +* **What makes Qt valuable?** + - **Cross-platform** nature + - **Scalability** from low-end devices to complex desktop apps + - **Tools** and **documentation** + - **Maintainability**, **stability** and **compatibility** + - A large **developer ecosystem** + +----------------------------------------------- + +A new version of Qt must keep and improve this features while adjusting to the new market demands + +--- + +## Hot points + +* Embedded and connected (cloud-based) devices +* Touch screens +* Low-end chipsets +* Microcontrollers +* Multi-screen desktop devices +* Artificial intelligence +* Qt tooling + +------------------------------------------------ + +As such, the focus will be on those items that require architectural changes within Qt and cannot be done without breaking compatibility with Qt 5. + +--- + +## Next-generation QML + +* Introduce strong typing +* Compile QML to efficient C++ native code +* Make JavaScript an optional feature of QML +* Remove QML versioning +* Remove the duplication of data structures between C++ and QML +* Avoid runtime generated data structures +* Support hiding implementation details +* Better tooling integration + +--- + +## Next-generation graphics + +* Lot of changes since Qt 5 + - *Vulkan* has been designed as successor of *OpenGL* + - Apple is pushing for *Metal* + - Microsoft got *Direct 3D* + +Qt must work seamlessly with all those APIs + +To make that possible, a new layer abstracting the graphics APIs called the ***Rendering Hardware Interface*** (HRI) has to be defined + +-- + +With Qt 5, there is no unified solution for creating UIs that contain both 2D and 3D components, and it is impossible to sync animations and transitions frame-by-frame between 2D and 3D content. Qt 6 will solve this problem. + +-- + +Qt 6 aims to bring an unified theming/styling engine, which will allows us to get a native look and feel on desktop and mobile platforms to both Qt Widgets and Qt Quick. + +--- + +## Unified and consistent tooling + +* Qt Design Studio will be well integrated with tools like Photoshop, Sketch, Illustrator, Maya, 3D Max and others. +* Best-class tooling for C++, QML and Python +* Deprecate QMake in favor of CMake + +--- + +## Enhance C++ + +* Migrate codebase from C++11 to C++17 + +--- + +# Wrapping up + +Thank you for coming! \ No newline at end of file