<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Manuel Conde on Medium]]></title>
        <description><![CDATA[Stories by Manuel Conde on Medium]]></description>
        <link>https://medium.com/@mcvendrell?source=rss-f23518ec3fae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ah_DAD6W3Lb5rB6zFDiR8A.jpeg</url>
            <title>Stories by Manuel Conde on Medium</title>
            <link>https://medium.com/@mcvendrell?source=rss-f23518ec3fae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 16:09:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mcvendrell/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to import an exported CSV file into a DynamoDB table]]></title>
            <link>https://mcvendrell.medium.com/how-to-import-an-exported-csv-file-into-a-dynamodb-table-02cf7cf08637?source=rss-f23518ec3fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/02cf7cf08637</guid>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[import]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Manuel Conde]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 20:06:52 GMT</pubDate>
            <atom:updated>2025-03-18T20:06:52.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*848ELyj9A_3VCzRV.png" /></figure><p>Sometimes you need to export your table and import in another table. It’s an easy operation in SQL, but with DynamoDB the process is different.</p><p>So I invest some hours creating and testing this script in Python to easely export and import the common used data I usually manage (String, Number, List and Map values).</p><p>They key here is to note that, when you use (and I do) the <strong>“Download Data as CSV”</strong> option available in the AWS Management Console, all goes fine unless you have List(L) or Map(M) values.</p><p>This is an example of my original CSV data file generated by AWS:</p><pre>&quot;region&quot;,&quot;id&quot;,&quot;communications&quot;,&quot;name&quot;,&quot;role&quot;,&quot;skills&quot;<br>&quot;ES&quot;,&quot;a&quot;,&quot;&quot;,&quot;Admin&quot;,&quot;admin&quot;,&quot;&quot;<br>&quot;ES&quot;,&quot;b&quot;,&quot;{&quot;&quot;vote&quot;&quot;:{&quot;&quot;S&quot;&quot;:&quot;&quot;Y&quot;&quot;},&quot;&quot;ads&quot;&quot;:{&quot;&quot;S&quot;&quot;:&quot;&quot;Y&quot;&quot;}}&quot;,&quot;Pablo Mármol&quot;,&quot;worker&quot;,&quot;[{&quot;&quot;S&quot;&quot;:&quot;&quot;barista&quot;&quot;}]&quot;<br>&quot;ES&quot;,&quot;c&quot;,&quot;{&quot;&quot;vote&quot;&quot;:{&quot;&quot;S&quot;&quot;:&quot;&quot;Y&quot;&quot;},&quot;&quot;ads&quot;&quot;:{&quot;&quot;S&quot;&quot;:&quot;&quot;Y&quot;&quot;}}&quot;,&quot;Pedro Picapiedra&quot;,&quot;worker&quot;,&quot;[{&quot;&quot;S&quot;&quot;:&quot;&quot;barista&quot;&quot;},{&quot;&quot;S&quot;&quot;:&quot;&quot;bartender&quot;&quot;}]&quot;</pre><p>All quoted and separated by , The problem here is that inner L and M values also are separated by , so a basic scripting operation to split fields by comma will not work.</p><h3>First step: reconvert with Excel</h3><p>The easiest way to solve this problem is to use Excel to import CSV file, go to “Data” -&gt; “From Text/CSV” and use comma as separator fields. Then you will end with something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1BXoZX9wNNOGF_MdmYc3Q.png" /><figcaption>Excel import</figcaption></figure><p>If you save it now as CSV, your file contains now this:</p><pre>region;id;communications;name;role;skills<br>ES;a;;Admin;admin;<br>ES;b;&quot;{&quot;&quot;vote&quot;&quot;:{&quot;&quot;S&quot;&quot;:&quot;&quot;Y&quot;&quot;},&quot;&quot;ads&quot;&quot;:{&quot;&quot;S&quot;&quot;:&quot;&quot;Y&quot;&quot;}}&quot;;Pablo Mármol;worker;&quot;[{&quot;&quot;S&quot;&quot;:&quot;&quot;barista&quot;&quot;}]&quot;<br>ES;c;&quot;{&quot;&quot;vote&quot;&quot;:{&quot;&quot;S&quot;&quot;:&quot;&quot;Y&quot;&quot;},&quot;&quot;ads&quot;&quot;:{&quot;&quot;S&quot;&quot;:&quot;&quot;Y&quot;&quot;}}&quot;;Pedro Picapiedra;worker;&quot;[{&quot;&quot;S&quot;&quot;:&quot;&quot;barista&quot;&quot;},{&quot;&quot;S&quot;&quot;:&quot;&quot;bartender&quot;&quot;}]&quot;</pre><p>And now, we are ready to work with scripting in Python.</p><h3>Last step: execute Python script</h3><p>Now you only need to configure and execute this Python script I wrote and tested for some hours.</p><pre># Before use, install dependencies<br># pip install awscli<br># pip install boto3<br># Additionally, AWS should be configured<br># aws configure<br><br>import boto3<br>import csv<br>import json<br><br># INTRUCTIONS<br># Open the CSV file in Excel and go to &quot;Data&quot; -&gt; &quot;From Text/CSV&quot;<br># This will change original dynamodb export columns delimiter from , to ;<br># Save the file with a new name and close Excel. This is necessary only if you have List or Map fields in your CSV<br>#      because the inner fields are separated by &quot;,&quot; and this will cause issues with columns, so columns now are separated by &quot;;&quot;<br># If you don&#39;t change the delimiter, you will have to change the delimiter at the end in the code from ; to ,<br># Now, configure params below and run the script<br><br># True = logs in console<br>debug = False<br><br># Configure params<br>table_name = &#39;YOU_TABLE_HERE&#39;<br>csv_file_path = &#39;C:/Temp/usersexcel.csv&#39;<br><br># Access to dynamodb<br>dynamodb_client = boto3.client(&#39;dynamodb&#39;, region_name=&#39;eu-west-1&#39;)<br><br>def parse_value(value):<br>    &quot;&quot;&quot;Converts values to lists, maps, or leaves them as string/number.&quot;&quot;&quot;<br>    if value == &quot;&quot;:<br>        return None<br><br>    try:<br>        parsed = json.loads(value)<br>        return parsed<br>    except json.JSONDecodeError:<br>        return value<br><br>def convert_item(row):<br>    &quot;&quot;&quot;Transform a CSV row in a DynamoDB format.&quot;&quot;&quot;<br>    item = {}<br><br>    for key, value in row.items():<br>        parsed_value = parse_value(value)<br><br>        if debug:<br>            print(f&quot;Key -&gt; {key} -- {parsed_value}&quot;)<br><br>        if parsed_value is None:<br>            continue<br><br>        # Handle types<br>        if key in [&quot;skills&quot;] and isinstance(parsed_value, list):<br>            item[key] = {&quot;L&quot;: parsed_value}  # List of strings<br>        elif key == &quot;communications&quot; and isinstance(parsed_value, dict):<br>            item[key] = {&quot;M&quot;: parsed_value}  # Map<br>        elif key in [&quot;totalVotes&quot;] and isinstance(parsed_value, (int, float, str)):<br>            item[key] = {&quot;N&quot;: str(parsed_value)}  # Numbers<br>        else:<br>            item[key] = {&quot;S&quot;: str(parsed_value)}  # Default as string<br><br>    return item<br><br># Read CSV file and process each row<br>with open(csv_file_path, mode=&#39;r&#39;, encoding=&#39;ISO-8859-1&#39;) as file:<br>    reader = csv.DictReader(file, delimiter=&#39;;&#39;)<br>    count = 0<br><br>    for row in reader:<br>        count += 1<br><br>        print(f&quot;Processing row {count}...&quot;)<br>        if debug:<br>            print(&quot;-----------------------------------------------------------------------------------------------------&quot;)<br>            print(&quot;row in raw -&gt;&quot;, row)<br><br>        item = convert_item(row)<br><br>        if debug:<br>            print(&quot;Parsed -&gt;&quot;, item)<br>            # print(json.dumps(item, indent=2))<br><br>        dynamodb_client.put_item(TableName=table_name, Item=item)<br><br>print(f&quot;✅ Data from {csv_file_path} has been successfully pushed to DynamoDB table {table_name}.&quot;)</pre><p>Will import all values with the right type.</p><p>You can check the code in my <a href="https://github.com/mcvendrell/DynamoDB-CSV-import">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02cf7cf08637" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to integrate Fusion Solar (from Huawei) with Alexa]]></title>
            <link>https://mcvendrell.medium.com/how-to-integrate-fusion-solar-from-huawei-with-alexa-377698ab058c?source=rss-f23518ec3fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/377698ab058c</guid>
            <category><![CDATA[huawei]]></category>
            <category><![CDATA[solar]]></category>
            <category><![CDATA[alexa]]></category>
            <category><![CDATA[alexa-skills]]></category>
            <category><![CDATA[fusion]]></category>
            <dc:creator><![CDATA[Manuel Conde]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 12:43:44 GMT</pubDate>
            <atom:updated>2025-02-24T12:11:20.035Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*XFZY6K1YUdUS1wcOvF8wBQ.png" /></figure><p>Recently, I had solar panels installed with a Huawei inverter, model SUN2000.</p><p>After seeing that the Fusion Solar app offers a lot of data related to energy generation and consumption, I was intrigued by the idea of whether it would be possible to integrate the information from the Fusion Solar app with Alexa.</p><p>After a quick search on Google, quite a few people were asking the same thing in Huawei’s own forums, but no one seemed to have found a solution, as Huawei does not offer any type of integration for Smart Home devices.</p><p>However, some people had found a solution to integrate Fusion Solar information into Home Assistant, which is an open-source system for Smart Home that uses Raspberry Pi devices or home servers to manage all the integrated devices.</p><p>I found those people here: <a href="https://github.com/tijsverkoyen/HomeAssistant-FusionSolar">https://github.com/tijsverkoyen/HomeAssistant-FusionSolar</a></p><p>Specifically, they discovered that the information generated by the kiosk mode (a customized control panel that offers very specific information chosen by the manufacturer) offered by Fusion Solar could be used, and also that, by knowing your installer’s data or becoming your own installer for your solar installation, one could access an internal API offered by Fusion Solar for installers through OpenAPI or NorthboundAPI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*-lVuJIjBN36JUgzfV6O8ww.png" /><figcaption>Some data offered by Fusion Solar website</figcaption></figure><p>Since, in my particular case, my only intention was to know from Alexa the power currently being generated (just out of curiosity and to avoid having to access the Fusion Solar app), the data offered by kiosk mode was sufficient for my purpose. However, it should be noted that the kiosk mode has a small issue: the data is cached for 30 minutes, so the information is not accessible in real time, but with a 30-minute delay. If this doesn’t work for you, you’ll have to deal with the API mode.</p><p>On the other hand, I discovered that it was quite easy to program your own skill for Alexa. Simply by following Amazon’s own tutorial (which takes about 30 minutes), where they explain how to create your first skill, you already have enough information.</p><p>With all this information, I got to work.</p><h3>Step one: get the data</h3><p>While the <a href="https://github.com/tijsverkoyen/HomeAssistant-FusionSolar">Github page for Home Assistant for Fusion Solar</a> tells you how to obtain the kiosk mode URL to integrate it into their system (on the Fusion Solar website, at the top right, there is the Kiosk icon), it does not clarify where they obtain the data in JSON format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*phrBebUFpOYlN5gRAefJIQ.png" /><figcaption>Where to activate kiosk mode</figcaption></figure><p>Because in reality, the URL that gives you the kiosk mode is a webpage that runs some JavaScript files and generates a visible page with statistics and a power generation graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*2s-0E7M6P-MEEqKSA-08yg.png" /><figcaption>Some of the data you could see in kiosk mode</figcaption></figure><p>The URL of the website that offers kiosk mode has this format:</p><p><a href="https://uni001eu5.fusionsolar.huawei.com/pvmswebsite/nologin/assets/build/cloud.html#/kiosk?kk=xxxxxxxxxxxxxxxxxxxxxxxxxxxx">https://uni001eu5.fusionsolar.huawei.com/pvmswebsite/nologin/assets/build/cloud.html#/kiosk?kk=xxxxxxxxxxxxxxxxxxxxxxxxxxxx</a></p><p>and in it, the only thing that stands out is the kk parameter, which gives us a unique generated token for our installation, with a validity of 1 year from the time it is generated. After that year, a new token must be generated.</p><p>If you analyze that page in the browser’s Dev Tools, you will see a call to the REST service, from where it gets the data displayed on that webpage. Specifically, the call is this one:</p><p><a href="https://uni001eu5.fusionsolar.huawei.com/rest/pvms/web/kiosk/v1/station-kiosk-file?kk=xxxxxxxxxxxxxxxxxxxxxxx">https://uni001eu5.fusionsolar.huawei.com/rest/pvms/web/kiosk/v1/station-kiosk-file?kk=xxxxxxxxxxxxxxxxxxxxxxx</a></p><p>As you can see, it uses the same token to obtain the information. The call returns several data points (including those for the graph to be represented, which are many) and, specifically, the information we want is in the data field. A small problem we encounter with the response of this data is that it comes in escaped format, so it is not readable at first glance. Simply, by unescaping the content, we already have the information legible.</p><p>Several data come, but in my case, the only one that interests me is the current power, which is found in <em>data.realKpi.realTimePower</em>.</p><p>We already have a way to easily obtain the data we need.</p><h3>Second step: integrate it into an Alexa skill</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*gqNAtAMzacRorfNE" /></figure><p>Since the purpose of this tutorial is not to explain how to create an Alexa skill, as the Alexa tutorial explains it perfectly, what I am going to provide you with is the final code that the Alexa skill executes to return the information to me through a voice command.</p><p>The only thing I will add is that my intention was for Alexa to give me the information with a single and simple command, for which I have used the “LaunchRequestHandler” to directly execute my code without having to give a second command to execute a custom intent. As the invocation name, I have chosen “fusion solar” (at least two words).</p><p>I clarify this because the tutorial specifies that Alexa skills must have an invocation name, such as “Alexa, open fusion solar” and then, in the custom intent where you have your code, you assign one or more utterances that call that intent (for example, “give me the power”). That forced me to say long phrases like the following: “Alexa, open fusion solar and give me the power”. To avoid this, I decided to put the code directly into the launcher and thus avoid having to say an execution phrase that calls the intent.</p><p>That said, this is how I left the launcher:</p><pre>const Alexa = require(&#39;ask-sdk-core&#39;);<br>const axios = require(&#39;axios&#39;);<br>const unscape = require(&#39;unescape&#39;);<br><br>const LaunchRequestHandler = {<br>    canHandle(handlerInput) {<br>        return Alexa.getRequestType(handlerInput.requestEnvelope) === &#39;LaunchRequest&#39;;<br>    },<br>    async handle(handlerInput) {<br>        try {<br>            const response = await axios.get(`https://uni001eu5.fusionsolar.huawei.com/rest/pvms/web/kiosk/v1/station-kiosk-file?kk=YOUR_TOKEN_HERE`);<br>            const data = JSON.parse(unscape(response.data.data));<br>            const power = Math.round(data.realKpi.realTimePower * 10) / 10;<br>            let speechText;<br>            <br>            switch (true) {<br>                case (power &lt;= 0.5):<br>                    speechText = `La potencia actual es muy baja, de solo ${power} kilovatios.`;<br>                    break;<br>                case (power &gt; 0.5 &amp;&amp; power &lt;= 1):<br>                    speechText = `La potencia actual es baja, de solo ${power} kilovatios.`;<br>                    break;<br>                case (power &gt; 1 &amp;&amp; power &lt;= 2):<br>                    speechText = `La potencia actual es media, de ${power} kilovatios.`;<br>                    break;<br>                case (power &gt; 2 &amp;&amp; power &lt;= 3):<br>                    speechText = `La potencia actual es alta, de ${power} kilovatios.`;<br>                    break;<br>                case (power &gt; 3):<br>                    speechText = `La potencia actual es muy alta, de ${power} kilovatios. ¡Vamos a todo tren!`;<br>                    break;<br>                default:<br>                    speechText = `Valor desconocido`;<br>                    console.log(&quot;Valor no reconocido&quot;);<br>            }<br><br>            return handlerInput.responseBuilder<br>                .speak(speechText)<br>                .getResponse();<br>        } catch (error) {<br>            return handlerInput.responseBuilder<br>                .speak(`Lo siento, hubo algún error al leer los datos del inversor.`)<br>                .getResponse();<br>        }<br>    }<br>};<br><br>... rest of default code</pre><p>It should be noted here that I have used the axios library to make the call to the REST service, and the unescape library to unescape the data. Both must be included in the lambda’s file package.json.</p><pre> &quot;dependencies&quot;: {<br>    &quot;ask-sdk-core&quot;: &quot;^2.7.0&quot;,<br>    &quot;ask-sdk-model&quot;: &quot;^1.19.0&quot;,<br>    &quot;aws-sdk&quot;: &quot;^2.326.0&quot;,<br>    &quot;axios&quot;: &quot;^1.7.9&quot;,<br>    &quot;unescape&quot;: &quot;^1.0.1&quot;<br>  }</pre><h3>Third step: ask Alexa</h3><p>Well, with these two things, everything would be ready to have our personalized skill on Alexa. The ultimate test comes when I say to the Fire-TV: “Alexa, open fusion solar” and Alexa responds with a simple phrase: “The current power is medium, at 1.2 kilowatts.”</p><p>Next comes the question I have seen the most in forums about skills that only you will use at home: do I have to publish the skill in the Market? The answer, according to my research, seems to be no. You can leave your skill in developer mode and you won’t need to publish it (which would be detrimental to you, because remember that you had to put your personal token in the URL that calls the REST service, and you need to renew that token every year). The only thing you need to keep in mind for this to work is that your developer account and the account you use with Alexa must be the same.</p><p>And done! I already have some information about solar panels integrated into Alexa. In total, gathering and understanding the information, watching the Alexa skills tutorial, finding and refining the REST data, and programming and testing the skill, barely took me an afternoon (about 4 hours). So I think it’s quite accessible for anyone.</p><p>Surely, if you have more Smart Home devices, you can come up with ideas to integrate turning them off or on at specific times of the day, simply by asking Alexa. I hope it has been useful to you.</p><p>You can find the full code in my GitHub: <a href="https://github.com/mcvendrell/alexa-skill-for-fusion-solar?tab=readme-ov-file">https://github.com/mcvendrell/alexa-skill-for-fusion-solar?tab=readme-ov-file</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=377698ab058c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cómo integrar Fusión Solar (de Huawei) con Alexa]]></title>
            <link>https://mcvendrell.medium.com/c%C3%B3mo-integrar-fusi%C3%B3n-solar-de-huawei-con-alexa-7f71d6a3b6ae?source=rss-f23518ec3fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f71d6a3b6ae</guid>
            <category><![CDATA[fusion]]></category>
            <category><![CDATA[alexa]]></category>
            <category><![CDATA[alexa-skills]]></category>
            <category><![CDATA[huawei]]></category>
            <category><![CDATA[solar]]></category>
            <dc:creator><![CDATA[Manuel Conde]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 12:05:30 GMT</pubDate>
            <atom:updated>2025-02-19T12:05:30.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*XFZY6K1YUdUS1wcOvF8wBQ.png" /></figure><p>Recientemente me han instalado unas placas solares con un inversor de Huawei, modelo SUN2000.</p><p>Tras ver que la aplicación Fusión Solar ofrece muchos datos relativos a la generación y consumo de energía, me intrigó la idea de si sería posible integrar la información de la aplicación Fusión Solar con Alexa.</p><p>Tras unas búsquedas rápidas en Google, bastante gente preguntaba por lo mismo en los propios foros de Huawei, pero ninguna persona parecía haber dado con una solución, ya que Huawei no ofrece ningún tipo de integración para dispositivos Smart Home.</p><p>Sin embargo, algunas personas habían encontrado una solución para integrar la información de Fusión Solar en Home Assistant, que es un sistema open source para Smart Home que usa dispositivos Raspberry Pi o servidores caseros para gestionar todos los dispositivos integrados.</p><p>Esas personas las encontré aquí: <a href="https://github.com/tijsverkoyen/HomeAssistant-FusionSolar">https://github.com/tijsverkoyen/HomeAssistant-FusionSolar</a></p><p>En concreto, descubrieron que se podía usar la información generada por el modo kiosco (un tablero de control personalizado que ofrece información muy concreta que el fabricante elige) que ofrece Fusión Solar y también que, conociendo los datos de tu instalador o haciéndote tú mismo instalador de tu propia instalación solar, se puede acceder mediante OpenAPI o NorthboundAPI a una API interna que Fusión Solar ofrece para instaladores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*-lVuJIjBN36JUgzfV6O8ww.png" /><figcaption>Datos que ofrece la app de Fusión Solar</figcaption></figure><p>Puesto que, en mi caso particular, mi única intención era conocer desde Alexa la potencia que se está generando actualmente (solo por curiosidad y por no tener que acceder a la app de Fusión Solar), los datos que ofrece el modo kiosco eran suficientes para mi propósito. Eso sí, hay que advertir que el modo kiosco tiene un pequeño problema: los datos están cacheados durante 30 minutos, por lo que la información no está accesible en tiempo real, sino con 30 minutos de desfase. Si a ti esto no te sirve, tendrás que pelearte con el modo API.</p><p>Por otro lado, descubrí que era bastante fácil programarte tu propia skill para Alexa. Simplemente con seguir el tutorial de la propia Amazon (que son unos 30 minutos), donde explican cómo crearte tu primera skill, ya dispones de la información suficiente.</p><p>Con toda esta información, me puse manos a la obra.</p><h3><strong>Primer paso: obtener los datos</strong></h3><p>Si bien en la <a href="https://github.com/tijsverkoyen/HomeAssistant-FusionSolar">página de Github del Home Assistant</a> para Fusión Solar te dicen como obtener la URL del modo kiosco para integrarlo en su sistema (en la web de Fusión Solar, arriba a la derecha, está el icono de Kiosk), no aclaran de dónde obtienen los datos en formato json.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*phrBebUFpOYlN5gRAefJIQ.png" /><figcaption>Dónde obtener el modo kiosko</figcaption></figure><p>Porque en realidad, la URL que te da el modo kiosco es una página web que ejecuta unos archivos javascript y generan una página visible con estadísticas y una gráfica de potencia generada.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*2s-0E7M6P-MEEqKSA-08yg.png" /><figcaption>Parte de los datos que se ven en el modo kiosko</figcaption></figure><p>La URL de la página web que ofrece el modo kiosco tiene este formato:</p><p><a href="https://uni001eu5.fusionsolar.huawei.com/pvmswebsite/nologin/assets/build/cloud.html#/kiosk?kk=xxxxxxxxxxxxxxxxxxxxxxxxxxxx">https://uni001eu5.fusionsolar.huawei.com/pvmswebsite/nologin/assets/build/cloud.html#/kiosk?kk=xxxxxxxxxxxxxxxxxxxxxxxxxxxx</a></p><p>y en él, lo único que destaca es el parámetro kk, que nos da un token generado único de nuestra instalación, con una validez de 1 año desde que se genera. Pasado ese año, hay que volver a generar un nuevo token.</p><p>Si analizas esa página en las Dev Tools del navegador, verás una llamada al servicio REST, de donde obtiene los datos que se muestran en esa página web. En concreto, la llamada es esta:</p><p><a href="https://uni001eu5.fusionsolar.huawei.com/rest/pvms/web/kiosk/v1/station-kiosk-file?kk=xxxxxxxxxxxxxxxxxxxxxxx">https://uni001eu5.fusionsolar.huawei.com/rest/pvms/web/kiosk/v1/station-kiosk-file?kk=xxxxxxxxxxxxxxxxxxxxxxx</a></p><p>Como se ve, usa el mismo token para obtener la información. La llamada devuelve varios datos (incluídos los de la gráfica a representar, que son muchos) y, en concreto, la información que queremos está en el campo data. Un pequeño problema que nos encontramos con la respuesta de este dato, es que viene en formato escapado, por lo que no es legible a simple vista. Simplemente, desescapando el contenido ya tenemos la información legible.</p><p>Vienen varios datos, pero en mi caso el único que me interesa es el de la potencia actual, que se encuentra en data.realKpi.realTimePower.</p><p>Ya tenemos una forma de obtener el dato que necesitamos fácilmente.</p><h3><strong>Segundo paso: integrarlo en una skill de Alexa</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*QJox5rXiWmzYdQrV" /></figure><p>Como no es el propósito de este tutorial explicar cómo se crea una skill de Alexa, que para eso el tutorial de Alexa lo explica perfectamente, lo que os voy a poner es el código final que ejecuta la skill de Alexa para devolverme la información a través de un comando vocal.</p><p>Lo único que sí que voy a añadir es que mi intención era que Alexa me diese la información con un único y sencillo comando, para lo cual lo que he hecho es usar el “LaunchRequestHandler” para ejecutar directamente mi código sin tener que darle un segundo comando que ejecute un intent personalizado. Como nombre de invocación he elegido “fusión solar” (mínimo son dos palabras).</p><p>Aclaro esto porque en el tutorial se especifica que las skills de Alexa deben tener un nombre de invocación, como por ejemplo “Alexa, abre Fusión Solar” y, a continuación, en el intent personalizado donde tienes tu código, asignas una o varias frases de ejecución que llaman a ese intent (por ejemplo, “dame la potencia”). Eso me obligaba a decir frases largas como la siguiente: “Alexa, abre Fusión Solar y dame la potencia”. Para evitar esto, lo que decidí fue meter el código directamente en el launcher y evitar, de esa forma, tener que decir una frase de ejecución que llame al intent.</p><p>Dicho esto, así es como dejé el launcher:</p><pre>const Alexa = require(&#39;ask-sdk-core&#39;);<br>const axios = require(&#39;axios&#39;);<br>const unscape = require(&#39;unescape&#39;);<br><br>const LaunchRequestHandler = {<br>    canHandle(handlerInput) {<br>        return Alexa.getRequestType(handlerInput.requestEnvelope) === &#39;LaunchRequest&#39;;<br>    },<br>    async handle(handlerInput) {<br>        try {<br>            const response = await axios.get(`https://uni001eu5.fusionsolar.huawei.com/rest/pvms/web/kiosk/v1/station-kiosk-file?kk=YOUR_TOKEN_HERE`);<br>            const data = JSON.parse(unscape(response.data.data));<br>            const power = Math.round(data.realKpi.realTimePower * 10) / 10;<br>            let speechText;<br>            <br>            switch (true) {<br>                case (power &lt;= 0.5):<br>                    speechText = `La potencia actual es muy baja, de solo ${power} kilovatios.`;<br>                    break;<br>                case (power &gt; 0.5 &amp;&amp; power &lt;= 1):<br>                    speechText = `La potencia actual es baja, de solo ${power} kilovatios.`;<br>                    break;<br>                case (power &gt; 1 &amp;&amp; power &lt;= 2):<br>                    speechText = `La potencia actual es media, de ${power} kilovatios.`;<br>                    break;<br>                case (power &gt; 2 &amp;&amp; power &lt;= 3):<br>                    speechText = `La potencia actual es alta, de ${power} kilovatios.`;<br>                    break;<br>                case (power &gt; 3):<br>                    speechText = `La potencia actual es muy alta, de ${power} kilovatios. ¡Vamos a todo tren!`;<br>                    break;<br>                default:<br>                    speechText = `Valor desconocido`;<br>                    console.log(&quot;Valor no reconocido&quot;);<br>            }<br><br>            return handlerInput.responseBuilder<br>                .speak(speechText)<br>                .getResponse();<br>        } catch (error) {<br>            return handlerInput.responseBuilder<br>                .speak(`Lo siento, hubo algún error al leer los datos del inversor.`)<br>                .getResponse();<br>        }<br>    }<br>};<br><br>... resto del código que ya viene por defecto</pre><p>Hay que notar aquí que he hecho uso de la librería axios, para hacer la llamada al servicio REST, y la librería unescape para desescapar los datos. Ambas deben ser incluidas en el package.json de la lambda:</p><pre>  &quot;dependencies&quot;: {<br>    &quot;ask-sdk-core&quot;: &quot;^2.7.0&quot;,<br>    &quot;ask-sdk-model&quot;: &quot;^1.19.0&quot;,<br>    &quot;aws-sdk&quot;: &quot;^2.326.0&quot;,<br>    &quot;axios&quot;: &quot;^1.7.9&quot;,<br>    &quot;unescape&quot;: &quot;^1.0.1&quot;<br>  }</pre><h3><strong>Tercer paso: preguntar a Alexa</strong></h3><p>Pues con estas dos cosas ya estaría todo listo para tener nuestra skill personalizada en Alexa. La prueba definitiva viene cuando le digo al Fire-TV: “Alexa, abre Fusión Solar” y Alexa me contesta con una sencilla frase: “La potencia actual es media, de 1.2 kilowatios”.</p><p>A continuación, viene la pregunta que más he visto en los foros sobre las skills que solo vas a usar tú en tu casa: ¿tengo que publicar la skill en el Market? La respuesta, según he investigado, parece ser no. Puedes dejar tu skill en modo developer y no necesitarás publicarla (lo cual sería perjudicial para ti, porque recuerda que has tenido que poner tu token personal en la url que llama al servicio rest, y que debes renovar ese token cada año). Lo único que debes tener en cuenta para que esto funcione, es que tu cuenta de desarrollador y la cuenta con la que usas Alexa deben ser la misma.</p><p>¡Y listo! Ya tengo algo de información de los paneles solares integrada en Alexa. En total, recabar y entender la información, ver el tutorial de skills para Alexa, encontrar y refinar los datos REST y programar y probar la skill, apenas me llevaron una tarde (unas 4 horas). Así que creo que es bastante asequible para cualquiera.</p><p>Seguro que si tienes más dispositivos Smart Home se te ocurren ideas para integrar apagados o encendidos en momentos determinados del día, simplemente consultando a Alexa. Espero que te haya sido de utilidad.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f71d6a3b6ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Material: lazy loading Tabs content but only the first time it is accessed]]></title>
            <link>https://mcvendrell.medium.com/angular-material-lazy-loading-tabs-content-but-only-the-first-time-it-is-accessed-d2da9de10432?source=rss-f23518ec3fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2da9de10432</guid>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[tabs]]></category>
            <dc:creator><![CDATA[Manuel Conde]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 10:16:12 GMT</pubDate>
            <atom:updated>2025-01-13T10:17:28.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-gcAFGC_FBZF1UuDEoDwMw.png" /></figure><p>When working with Angular Material tabs, you might want to implement lazy loading for your tab content while ensuring the content persists once it’s loaded. By default, Angular Material detaches inactive tab content from the DOM, which can lead to unnecessary reloading every time you change the tab. Here’s how you can efficiently implement lazy loading with persistent tabs.</p><h3>The Challenge</h3><p>By default, &lt;ng-template matTabContent&gt; enables lazy loading for Angular Material tabs. However, once a tab is loaded, you might want the content to stay in memory to avoid reinitializing it when switching back. This is especially important for complex or stateful components. In my case, I use it to avoid reloading data (so avoid consuming API calls).</p><h3>The Solution</h3><p>Here’s my approach that ensures tabs are lazy-loaded initially but remain persistent after their first load:</p><p>In the component:</p><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-tabs-example&#39;,<br>  templateUrl: &#39;./tabs-example.component.html&#39;,<br>  styleUrls: [&#39;./tabs-example.component.css&#39;]<br>})<br>export class TabsExampleComponent {<br>  loadedTabs: boolean[] = [true, false, false];<br><br>  onTabChange(index: number): void {<br>    this.loadedTabs[index] = true;<br>  }<br>}</pre><p>Use a loadedTabs array in the component to track which tabs have been loaded. Also, update state with onTabChange()</p><p>In the template:</p><pre>&lt;mat-tab-group (selectedIndexChange)=&quot;onTabChange($event)&quot;&gt;<br>  &lt;mat-tab&gt;<br>    @if (loadedTabs[0]) {<br>      &lt;app-tab1-content /&gt;<br>    } @else {<br>      &lt;ng-template matTabContent&gt;<br>        &lt;app-tab1-content /&gt;<br>      &lt;/ng-template&gt;<br>    }<br>  &lt;/mat-tab&gt;<br><br>  &lt;mat-tab&gt;<br>    @if (loadedTabs[1]) {<br>      &lt;app-tab2-content /&gt;<br>    } @else {<br>      &lt;ng-template matTabContent&gt;<br>        &lt;app-tab2-content /&gt;<br>      &lt;/ng-template&gt;<br>    }<br>  &lt;/mat-tab&gt;<br><br>  &lt;mat-tab&gt;<br>    @if (loadedTabs[2]) {<br>      &lt;app-tab3-content /&gt;<br>    } @else {<br>      &lt;ng-template matTabContent&gt;<br>        &lt;app-tab3-content /&gt;<br>      &lt;/ng-template&gt;<br>    }<br>  &lt;/mat-tab&gt;<br>&lt;/mat-tab-group&gt;</pre><h3>Explanation</h3><p>Because the &lt;ng-template matTabContent&gt; directive ensures the content is only loaded when the tab is selected, we simply need yo use a single IF to decide when to use the directive or not.</p><p>After the content is loaded for the first time, it’s directly rendered instead of using the matTabContent template. This prevents Angular Material from detaching the DOM when switching tabs.</p><h3>Advantages of This Approach</h3><ul><li><strong>Improved Performance</strong>: Tabs are loaded only when needed, reducing the initial rendering time.</li><li><strong>State Preservation</strong>: Once a tab’s content is loaded, it remains persistent, improving user experience for stateful components.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2da9de10432" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to read an Oracle BLOB field containing text in VB.NET with the right encoding]]></title>
            <link>https://mcvendrell.medium.com/how-to-read-an-oracle-blob-field-containing-text-in-vb-net-with-the-right-encoding-870f4bec6bf2?source=rss-f23518ec3fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/870f4bec6bf2</guid>
            <dc:creator><![CDATA[Manuel Conde]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 12:22:10 GMT</pubDate>
            <atom:updated>2023-11-08T12:26:57.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*GJULo0pJIGRFRt-l0jELSg.png" /></figure><p>It may seem easy, but it took me two hours to find exactly the right solution to this problem. Let’s put ourselves in situation.</p><p>I “inherit” and old Oracle 10g DB with a table containing one field as a BLOB (Binary Large OBject) but, instead of being used to store an image or any other binary large object, it contains large texts (or not, just the possibility of containing text larger than 4000 chars).</p><p>The right choice for this case should be CLOB, not BLOB, but the guy who designed this DB chose BLOB and I should manage it.</p><p>Well, the theory was easy (once you know it, of course, not all people know what a binary field means): the data to retrieve is in a binary format and must be “transformed” to the text we want to obtain. How? Getting each byte of the file into an array and using functions that read the array and returns a text (<em>GetString(bytearray)</em>).</p><p>I’ve never done this before, but internet is full of examples. I found several, mostly for C#, but the idea is the same for VB. So by mixing the main ideas, I easily get the text inside the BLOB. Let’s check the string… uhmmm… something is not right, I see weird chars in the accented chararters (spanish texts).</p><p>Since I worked a lot with different databases and operating systems over all this years, I quickly indentified the problem: encoding.</p><p>This is my first VB.NET project, and the options I have to “extracting” the text once I read the binary data are limited to a set of common encondings: ASCII, UTF8, Unicode and a few others. Any of them worked with text.</p><p>So I went straight to the problem: what encoding was the DB using?</p><pre>SELECT VALUE FROM V$NLS_PARAMETERS WHERE PARAMETER = ‘NLS_CHARACTERSET’</pre><p>The response was: WE8MSWIN1252. A “subclass” of the classic Win1252.</p><p>Obviously, ASCII, UTF8, Unicode… will not print the right characters when using, e.g., Encoding.UTF8.GetString(bytearray).</p><p>Well, if there was not a <em>GetString()</em> function for Win1252 to retrieve the right chars, the logical solution was a transformation from Win1252 to UTF8, and then use Encoding.UTF8.GetString(bytearray)to retrieve something readable. I tried it and… it worked like a charm.</p><p>Here, the final code I wrote for testing purposes, in a table TEST with ID as number, and DATA as blob.</p><pre>Imports System.IO<br>Imports System.Text<br>Imports Oracle.ManagedDataAccess.Client<br>...<br><br>Dim conn = New OracleConnection(mConnString)<br>Dim blob As OracleBlob<br>&#39;Check values in https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding?view=netframework-4.7.2<br>Dim win1252 = Encoding.GetEncoding(1252)<br><br>conn.Open()<br><br>Dim Sql = &quot;select * from test&quot;<br>Dim sqlCommand = New OracleCommand(Sql, conn)<br>Dim data As OracleDataReader = sqlCommand.ExecuteReader()<br>While data.Read()<br>  &#39;Get the blob field (the blob is binary data encoded with DB NLS_CHARACTERSET value)<br>  &#39;We can get it as an array of consecutive encoded bytes. SELECT VALUE FROM V$NLS_PARAMETERS WHERE PARAMETER = &#39;NLS_CHARACTERSET&#39; will give the current DB encoding<br>  &#39;We are, currently, using WE8MSWIN1252 in Oracle, so win1252 (not the same, but very similar to ANSI) is the current encoding<br>  blob = data.GetOracleBlob(1)<br><br>  &#39;Setup a byte array with blob data length<br>  Dim bytANSI(blob.Length) As Byte<br>  &#39;Now, read data from blob var into our ANSI byte array<br>  blob.Read(bytANSI, 0, blob.Length)<br><br>  &#39;Value is saved in Oracle table as Win1252 encoding.<br>  &#39;To retrieve it as string, we need to transform it to one of the GetString() available methods<br>  &#39;UTF8 is one of the more used encodings, so we transform it to UTF8<br>  Dim bytUTF8 = Encoding.Convert(win1252, Encoding.UTF8, bytANSI)<br><br>  &#39;Finally, we have 2 byte arrays: on ANSI and on UTF8 encodings. To get the string, use GetString() from UTF8 byte array encoding<br>  Dim strTemp = Encoding.UTF8.GetString(bytUTF8)<br><br>  System.Console.WriteLine(strTemp)<br><br>  &#39;Save a file text with UTF8 and another with ANSI encoding to check that all is working fine<br>  File.AppendAllText(&quot;C:\Temp\textUTF8.txt&quot;, strTemp)<br>  File.AppendAllText(&quot;C:\Temp\textANSI.txt&quot;, strTemp, win1252)<br>End While<br>data.Close()<br>conn.Close()</pre><p>So, problem solved. I simply want to leave this little pill for myself (maybe I will need it in the future) and for other people with the same problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=870f4bec6bf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mis principios maestros tras 20 años de programación]]></title>
            <link>https://mcvendrell.medium.com/mis-principios-maestros-tras-20-a%C3%B1os-de-programaci%C3%B3n-7ea350a1bea4?source=rss-f23518ec3fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ea350a1bea4</guid>
            <category><![CDATA[guidelines]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[knowledge]]></category>
            <dc:creator><![CDATA[Manuel Conde]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 10:58:15 GMT</pubDate>
            <atom:updated>2022-03-29T10:58:15.214Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Esta es una traducción al español de un </em><a href="https://alexewerlof.medium.com/my-guiding-principles-after-20-years-of-programming-a087dc55596c"><em>artículo</em></a><em> que me pareció muy interesante, dada su naturaleza, la experiencia de </em><a href="https://alexewerlof.medium.com/"><em>Alex</em></a><em> y lo de acuerdo que estoy en, prácticamente, todos los puntos que cita.</em></p><p>He estado programando desde 1999 y este año he programado, oficialmente, durante más de 20 años. Empecé con Basic pero pronto pasé a Pascal y C y luego aprendí programación orientada a objetos (POO) con Delphi y C++. En 2006 comencé con Java y en 2011 comencé con JavaScript. He trabajado con una amplia gama de empresas, desde robótica, tecnología financiera, tecnología médica hasta medios y telecomunicaciones. A veces tenía un papel diferente como investigador, CTO, TPM (director técnico de productos), profesor, arquitecto de sistemas o TL (líder técnico), pero siempre he estado programando. He trabajado en algunos productos que sirvieron a millones de personas y en algunos que fallaron antes de ser lanzados. Trabajé como consultor e incluso tuve mi propia startup. He dedicado mucho tiempo a proyectos de código abierto, proyectos de código cerrado y proyectos internos de código abierto (código propietario desarrollado por una comunidad dentro de la empresa). He trabajado con pequeños microcontroladores hasta aplicaciones móviles y de escritorio, servidores en la nube y, últimamente, <em>serverless</em>.</p><p>Para mi 20 aniversario de programación, intenté enumerar los principios fundamentales que se han acumulado a lo largo de los años como mis principios maestros a lo largo de mi carrera:</p><ol><li>No pelees con las herramientas: bibliotecas, lenguaje, plataforma, etc. Usa tantas construcciones nativas como sea posible. No doblegues la tecnología, pero tampoco doblegues el problema. Elije la herramienta adecuada para el trabajo o tendrás que encontrar el trabajo adecuado para la herramienta que elegiste.</li><li>No escribes el código para las máquinas, lo escribes para tus compañeros y para ti mismo en el futuro (a menos que sea un proyecto descartable o estés escribiendo ensamblador). Escríbelo para los más inexpertos como referencia.</li><li>Cualquier pieza de software significativa y gratificante es el resultado de la colaboración. Comunícate de manera efectiva y colabora abiertamente. Confía en los demás y gánate su confianza. Respeta a las personas más que al código. Predica con el ejemplo. Convierte a tus seguidores en líderes.</li><li>Divide y vencerás. Escribe módulos aislados con responsabilidades separadas que estén débilmente acoplados. Prueba cada parte por separado y en conjunto. Mantén los test cercanos a la realidad, pero testea también los casos extremos.</li><li>Recházate a ti mismo. No seas la persona a la que acudir para obtener el código. Optimízalo para que las personas encuentren su camino corrigiendo errores y agregando funciones al código. Libérate para pasar al siguiente proyecto/empresa. No poseas el código o nunca crecerás más allá de eso.</li><li>La seguridad viene en capas: cada capa debe evaluarse individualmente pero también en relación con el todo. El riesgo es una decisión empresarial y tiene relación directa con la vulnerabilidad y la probabilidad. Cada producto/organización tiene un nivel de riesgo diferente (el riesgo que están dispuestos a asumir para obtener una ganancia mayor). A menudo, estas 3 preocupaciones luchan entre sí: UX, Seguridad, Rendimiento.</li><li>Date cuenta de que cada código tiene un ciclo de vida, y que morirá. A veces muere en su infancia antes de ver la luz de la producción. Siéntete en paz con dejarlo ir. Conoce la diferencia entre 4 categorías de características y dónde poner tu tiempo y energía:<br><strong>Núcleo</strong>: como el motor en un automóvil. El producto no tiene sentido sin él.<br><strong>Necesario</strong>: como la rueda de repuesto de un coche. Rara vez se usa, pero cuando es necesario, su función decide el éxito del sistema.<br><strong>Valor añadido</strong>: como el portavasos de un coche. Es bueno tenerlo, pero el producto es perfectamente utilizable sin él.<br><strong>Punto de venta único</strong>: la razón principal por la que las personas deberían comprar tu producto en lugar del de tus rivales. Por ejemplo, tu automóvil es el mejor vehículo todoterreno.</li><li>No asocies tu identidad a tu código. No asocies la identidad de nadie a su código. Date cuenta de que las personas están separadas de su creaciones. No tomes las críticas al código como algo personal, pero ten mucho cuidado al criticar el código de otros.</li><li>La deuda tecnológica es como la comida rápida. De vez en cuando es aceptable, pero si te acostumbras, matará al producto más rápido de lo que crees (y de forma dolorosa).</li><li>Al tomar decisiones sobre la solución, en igualdad de condiciones, opta por esta prioridad:<br><strong>Seguridad &gt; Confiabilidad &gt; Usabilidad (Accesibilidad y UX) &gt; Mantenibilidad &gt; Simplicidad (Experiencia del desarrollador/DX) &gt; Brevedad (longitud del código) &gt; Finanzas &gt; Rendimiento</strong><br>Pero no sigas esto a ciegas porque depende de la naturaleza del producto. Como en cualquier carrera, cuanta más experiencia ganes, más podrás encontrar el equilibrio adecuado para cada situación. Por ejemplo, al diseñar un motor de juegos el rendimiento tiene la máxima prioridad, pero al crear una aplicación bancaria, la seguridad es el factor más importante.</li><li>La propagación de errores se llama <strong>copiar y pegar</strong>. Así es como se reproducen. Siempre revisa lo que copias, siempre audita lo que importas. Los bugs se refugian en la complejidad. La “magia” está bien en mis dependencias, pero no en mi código.</li><li>No solo escribas código para el escenario ideal. Devuelve <em>buenos errores</em> que respondan por qué sucedió, cómo se detectó y qué se puede hacer para resolverlo. Valida todas las entradas del sistema (incluidas las entradas del usuario): falla pronto pero recupérate de los errores siempre que sea posible. Supón que el usuario tiene un arma: ¡pon suficiente esfuerzo en tus errores para convencerlo de que dispare a algo que no sea tu cabeza!</li><li>No uses <strong>dependencias </strong>a menos que el costo de importar, mantener, lidiar con sus casos extremos/errores y refactorizar cuando no satisfagan las necesidades sea significativamente menor que el código que ya tienes.</li><li>Mantente alejado del <a href="https://blog.daftcode.pl/hype-driven-development-3469fc2e9b22"><strong>hype-driven development</strong></a>. Pero aprende todo lo que puedas. Siempre ten <strong>proyectos mascota</strong>.</li><li>Sal de tu zona de confort. Aprende todos los días. <strong>Enseña</strong> lo que aprendes. Si eres el maestro, no estás aprendiendo. Exponte a otros lenguajes, tecnologías, cultura y mantén la curiosidad.</li><li>Un buen código no necesita documentación, pero un gran código está <strong>bien documentado</strong> para que cualquier persona que no haya sido parte del proceso de evolución, prueba y error y los requisitos que llevaron al estado actual, pueda ser productivo con él. Una característica no documentada es una característica que no existe. Una característica inexistente no debería tener código.</li><li>Evita la sobreescritura, la herencia y la inteligencia implícita tanto como sea posible. Escribe funciones puras. Son más fáciles de probar y razonar. Cualquier función que no sea pura debería ser una clase. Cualquier construcción de código que tenga una función diferente, debe tener un nombre diferente.</li><li>Nunca comiences a codificar (creando una solución) a menos que comprendas completamente el <strong>problema</strong>. Es muy normal pasar más tiempo escuchando y leyendo, que escribiendo código. Comprende el dominio antes de comenzar a codificar. Un problema es como un laberinto. Debes pasar, progresivamente, por el ciclo de código-prueba-mejora y explorar el espacio del problema hasta llegar al final.</li><li>No resuelvas un problema que no existe. No hagas <strong>programación especulativa</strong>. Solo permite que el código sea extensible si es una suposición validada de que se extenderá. Lo más probable es que, cuando se extienda, la definición del problema sea diferente de cuando escribiste el código. No hagas <strong>sobreingeniería</strong>: concéntrate en resolver el problema en cuestión y en una solución efectiva, implementada de manera eficiente.</li><li>El software es más divertido cuando se hace en compañía. Construye una <strong>comunidad</strong> sostenible. Escucha. Inspira. Aprende. Comparte.</li></ol><p>No pretendo ser una autoridad en el desarrollo de software. Esto es solo la sabiduría que obtuve en el camino. Estoy seguro de que esta lista será más madura después de otros 20 años.</p><p><em>P.d.-</em> <em>Esta es una traducción al español de un </em><a href="https://alexewerlof.medium.com/my-guiding-principles-after-20-years-of-programming-a087dc55596c"><em>artículo</em></a><em> que me pareció muy interesante, dada su naturaleza, la experiencia de </em><a href="https://alexewerlof.medium.com/"><em>Alex</em></a><em> y lo de acuerdo que estoy en, prácticamente, todos los puntos que cita.</em></p><p>Hasta ahí llega el artículo original. Desde mi otros más de 20 años de programación, me gustaría añadir un simple principio que me ha ayudado todo este tiempo, mucho más que cualquier otro: KISS (Keep It Simple, Stupid).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ea350a1bea4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How an iPhone and some technology help me with my father’s Alzheimer’s]]></title>
            <link>https://mcvendrell.medium.com/how-an-iphone-and-some-technology-help-me-with-my-fathers-alzheimer-s-5516a34625e7?source=rss-f23518ec3fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/5516a34625e7</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[iphone]]></category>
            <category><![CDATA[alzheimers]]></category>
            <category><![CDATA[care]]></category>
            <category><![CDATA[siri]]></category>
            <dc:creator><![CDATA[Manuel Conde]]></dc:creator>
            <pubDate>Fri, 25 Feb 2022 11:27:55 GMT</pubDate>
            <atom:updated>2022-02-25T11:27:55.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhzYbzQJCZWlEeoZJRGXOA.png" /></figure><p>My father has Alzheimer’s. I had been noticing it for a few years, but medical tests diagnosed it with certainty some time ago.</p><p>As a degenerative disease that it is, it is advancing and my father’s brain is diminishing in capacity. Fortunately, until now he is quite autonomous, and the things he usually does, he continues to do (he drives the usual routes, cooks simple things, does the laundry, shops, irons, goes out to the bar to talk with people and drink his coffee… normal activities that we do any).</p><p>However, in the part of learning or logic he no longer works well. He is not capable of learning new things, or relating simple concepts. This, which might seem unimportant, greatly complicates the taking of medicines, especially when they change. It also makes it impossible for him to understand how a mobile or a television remote works.</p><p>Since I don’t live with him, and until the time comes for him to come live with us, I have used some technology to be able to attend to him and, above all, understand what he explains to me “in his way”, remotely.</p><p>I have looked for cheap but functional solutions to solve the following problems:</p><ul><li>Locate my father always.</li><li>Locate his bag with his things (house keys, glasses, wallet, etc).</li><li>See my father in his house, through the different rooms.</li><li>That my father can call me from his cell phone without using the contacts.</li><li>That my father can know what pills he has to take according to the time of day</li></ul><h4>Locate my father and his things</h4><p>Before, my father used a Xiaomi Android phone which he understood a few things about. Through Google and his account, I could geo-locate him whenever he wanted, but I had to enter his account from a browser to do so. On the other hand, since many times I didn’t know where he left her bag around his house, I bought him some Tile devices to locate nearby objects via bluetooth, which also tell you the last known position (in case he left it somewhere).</p><p>I had two problems with this configuration: the hassle of locating my father through a web browser and that the Xiaomi disconnected the bluetooth when it felt like it, not being able to locate the objects.</p><p>Since I am an iPhone user, because I love the simplicity of iOS, I exchanged the phone for a second-hand, cheap and functional iPhone 6S, knowing that:</p><ul><li>Any problem with the phone is solved by buying another one, since the iOS backup allows you to recover all the settings of the phone from the cloud. In this way, nothing would change for my father in the future, it would always be the same phone.</li><li>The integration of iOS with my own iPhone makes it easy for me to locate my father in the easiest way in the world.</li><li>Siri could help me with vocal commands (Google too, but not to the level I intended to use it).</li></ul><p>So, after configuring the iPhone to the most basic possible (here Apple could create a special configuration that would simplify the whole system even more, such as the contacts, which my father is not able to understand), the first thing I did was to allow the track his iPhone from my account, so that it shows up whenever I look for him in the iOS “<strong>Find My”</strong> app. In this way, now I only have to say “Hey Siri, where is dad” and, automatically, his position appears on a map, without having to do anything else. <strong>First problem</strong>, fixed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*MOte-W4gIGPBtCfdU_NYbA.png" /><figcaption>“Find My” app and “Tile” app</figcaption></figure><p>The <strong>second problem</strong> was solved only by switching to the iPhone, because the bluetooth never failed again, so I always have my father’s bag located. The application has already helped me several times to find it around the house, because my father had left it somewhere unusual and he couldn’t find it.</p><h4>See my father</h4><p>The <strong>third problem</strong>, seeing my father and what he was doing, I solved by buying some cameras with remote control. In my case, a DLink Full HD with a turntable, speakers/microphone and night vision. This fixed several issues at once:</p><ul><li>It allows me to see my father at any time.</li><li>I can talk to him live, walkie-talkie style.</li><li>When he calls me to explain something “in his language” (because, unfortunately, he has lost vocabulary or calls one thing by the name of another), I look at the camera and see what he means.</li><li>When he wants me to put the football on TV, I show him step by step which TV remote to take (the one for the TV or the one for the decoder), which menu he has to go to to switch from TV to HDMI, and which channel he has to put at the end in the decoder). This may seem silly, but doing it without seeing what he was doing on screen was very difficult. I got to spend 30 minutes on the phone to get it on without the cameras. Now I do it in 1 minute or 2, at the most. You have to keep in mind that he doesn’t understand the buttons on the controls, if you tell him to “push it up” he doesn’t know what you mean, and when he hits it, sometimes he doesn’t point at the TV and doesn’t get to the menu where he should be (in your plan formed in your head).</li></ul><h4>Siri and iOS shortcuts to the rescue</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuvMjJSgjcyVDGL56fDvzw.jpeg" /><figcaption>Create a list of Favorites to call</figcaption></figure><p>The <strong>fourth problem</strong> started to occur recently: he no longer understands how the iPhone contacts works. He knows that all his friends are there, but he doesn’t know how to use it to call any of them (which, basically, is to click on the name and then on the phone icon or on the phone number). My first option was to add a Shortcut with the favorites so that I only had to click on “<em>Speed dial</em>” and then the person. It worked, but it limited him to calling only the people on that list.</p><p>Finally, I realized that I used the “<em>Hey Siri, call dad</em>” option a lot, so I taught him how to call with Siri. It worked the first afternoon, the next day he couldn’t remember, so I stuck a label on the back of the phone with the phrase “<em>Hey Siri, call</em> …” and that’s how I got him to always call with Siri. Now he knows that he can call any name in the contacts, so “…call Carlos” or “…call Maria” allows him to call his friends without having to use the contacts at all.</p><p>Finally, the <strong>fifth problem</strong>, the issue of the daily pills he takes, some in the morning and others at night, and which at first he took perfectly, also ended up getting complicated. He no longer knows which ones eat and when, even if it is written on a piece of paper: “in the morning: this and that, at night, so and so”. Too many instructions to process by himself and blocks. The obvious solution is that he called me every day to ask me, when he got up and after dinner. The only problem was that if I wasn’t reachable for some reason, he got nervous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*lSzfxNwTOVxIaJvssBocZw.png" /><figcaption>Shortcut to indicate the pills</figcaption></figure><p>I then remembered the topic of iOS <em>Shortcuts</em>, again: it is possible to program almost anything with <em>Shortcuts</em>. So, I started to see how I could make a shortcut that, either in the morning (before 12), or at night, would indicate the correct pills to take. Then, you just had to name it something that Siri can understand for it to run. And so it was: “<em>Hey Siri, what pills do I have to take</em>”. From that moment on, and to my father’s astonishment (I had to convince him that this “machine” is never going to be wrong and will always tell him the same thing as me), every time he asks to the phone, it tells him correctly what have to take. The phrase, obviously, is written on paper.</p><h3>Conclusions</h3><p>Technology can help you a lot with these situations. It is possible that, in the Google ecosystem on Android, the same thing could be done (or almost, the iOS Shortcuts are wonderful as they are integrated with Siri, so that my father does not have to interact with a graphical interface, but simply talk), but of course, having everything integrated between my iPhone and him (looking for my father, his things with <em>Tile</em>, although I could also be using <em>Airtags</em>, but he already had the <em>Tiles</em> bought) and having Siri always available to my father is making his life easier as an autonomous person.</p><p>We’ll stretch that autonomy as far as we can, as long as it’s safe. He is happy to remain autonomous, within his possibilities. Of not feeling like a burden to anyone, of being able to do things for himself.</p><p>And that’s very important because as soon as he stops doing things, that part of his brain will disappear and never come back. For this reason, and this is how their doctors also communicate it to me, it is important that we stretch their autonomy as much as possible.</p><p>Finally, the cost of the technology that I have used, in case it serves someone as a reference, is as follows:</p><ul><li>Second-hand iPhone 6S but with a 2-year warranty: 120€</li><li>Two Tile devices: 20€ each.</li><li>Four surveillance cameras: 50€ each.</li></ul><p>In total, 360€ in devices. It is little, very little, compared to the help that they are giving me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5516a34625e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[De cómo un iPhone y algo de tecnología me ayudan con el Alzheimer de mi padre]]></title>
            <link>https://mcvendrell.medium.com/de-c%C3%B3mo-un-iphone-y-algo-de-tecnolog%C3%ADa-me-ayudan-con-el-alzheimer-de-mi-padre-73a48dbb67fc?source=rss-f23518ec3fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/73a48dbb67fc</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[alzheimers]]></category>
            <category><![CDATA[ayuda]]></category>
            <category><![CDATA[siri]]></category>
            <category><![CDATA[iphone]]></category>
            <dc:creator><![CDATA[Manuel Conde]]></dc:creator>
            <pubDate>Fri, 25 Feb 2022 10:42:42 GMT</pubDate>
            <atom:updated>2022-02-25T10:42:42.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhzYbzQJCZWlEeoZJRGXOA.png" /></figure><p>Mi padre tiene Alzheimer. Se lo venía notando desde hace unos pocos años, pero las pruebas médicas lo diagnosticaron con certeza hace ya algún tiempo.</p><p>Como enfermedad degenerativa que es, va avanzando y el cerebro de mi padre va menguando en capacidades. Afortunadamente, hasta ahora es bastante autónomo, y las cosas que hace habitualmente, las sigue haciendo (conduce por trayectos de siempre, cocina cosas sencillas, hace la colada, la compra, plancha, sale al bar a charlar con gente y tomar su café… las actividades normales que hacemos cualquiera).</p><p>Sin embargo, en la parte de aprender o de lógica ya no opera bien. No es capaz de aprender cosas nuevas, o de relacionar conceptos sencillos. Esto, que podría parecer poco importante, complica mucho la toma de medicinas sobre todo cuando éstas cambian. También le hace imposible entender cómo funciona un móvil o un mando de televisión.</p><p>Dado que no vivo con él, y hasta que llegue el momento de que él venga a vivir con nosotros, he empleado alguna tecnología para poder atenderlo y, sobre todo, entender lo que me explica “a su manera”, en remoto.</p><p>He buscado soluciones económicas pero funcionales para resolver los siguientes problemas:</p><ul><li>Localizar a mi padre siempre.</li><li>Localizar su bolso con sus cosas (llaves de casa, gafas, cartera, etc).</li><li>Ver a mi padre en su casa, por las distintas habitaciones.</li><li>Que mi padre pueda llamarme desde su móvil sin usar la agenda.</li><li>Que mi padre pueda saber qué pastillas tiene que tomarse según la hora del día.</li></ul><h4>Localizar a mi padre y sus cosas</h4><p>Antes, mi padre usaba un teléfono Android de Xiaomi del que entendía algunas pocas cosas. Mediante Google y su cuenta, lo podía geo-localizar cuando quisiera, pero tenía que entrar desde un navegador a su cuenta para ello. Por otro lado, puesto que muchas veces no sabía donde dejaba el bolso por su casa, le compré unos dispositivos <em>Tile</em> para localizar objetos cercanos mediante bluetooth, que también te indican la última posición conocida (por si se lo dejaba olvidado en algún sitio).</p><p>Tenía dos problemas con esta configuración: el engorro de localizar a mi padre por navegador web y que el Xiaomi desconectaba el bluetooth cuando le daba la gana, no pudiendo localizar los objetos.</p><p>Puesto que soy usuario de iPhone, porque me encanta la sencillez de iOS, le cambié el teléfono por un iPhone 6S de segunda mano, económico y funcional, sabedor de que:</p><ul><li>Cualquier problema con el teléfono se soluciona comprando otro, ya que la copia de seguridad de iOS permite recuperar toda la configuración del teléfono desde la nube. De esta forma, nada cambiaría para mi padre en el futuro, sería el mismo teléfono siempre.</li><li>La integración de iOS con mi propio iPhone me facilita localizar a mi padre de la forma más fácil del mundo.</li><li>Siri podría ayudarme con comandos vocales (Google también, pero no al nivel al que lo pretendía usar).</li></ul><p>Así pues, tras configurar el iPhone a lo más básico posible (aquí Apple podría crear una configuración especial que permitiese simplificar aún más todo el sistema, como la agenda, que mi padre no es capaz de comprender), lo primero que hice fue permitir el seguimiento de su iPhone desde mi cuenta, de forma que me apareciese siempre que lo busque en la aplicación “<strong>Buscar</strong>” de iOS. De esta forma, ahora solo tengo que decir “<em>Oye Siri, donde está papá</em>” y, automáticamente, me aparece en un mapa su posición, sin tener que hacer nada más. <strong>Primer problema</strong>, solucionado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*MOte-W4gIGPBtCfdU_NYbA.png" /><figcaption>Aplicación “Buscar” y aplicación “Tile”</figcaption></figure><p>El <strong>segundo problema </strong>se solucionó solo al cambiar al iPhone, porque el bluetooth no volvió a fallar nunca, por lo que siempre tengo localizado el bolso de mi padre. Ya me ha ayudado varias veces la aplicación a encontrarlo por la casa, porque mi padre lo había dejado en algún sitio no habitual y no lo conseguía encontrar.</p><h4>Ver a mi padre</h4><p>El <strong>tercer problema</strong>, ver a mi padre y lo que hacía, lo solucioné comprando unas cámaras con control remoto. En mi caso, unas DLink Full HD con plataforma giratoria, altavoces/micrófono y visión nocturna. Esto solucionó varios problemas a la vez:</p><ul><li>Me permite ver a mi padre en cualquier momento.</li><li>Puedo hablar con él en directo, en plan walkie-talkie.</li><li>Cuando me llama para explicarme algo “en su idioma” (porque, desafortunadamente, ha perdido vocabulario o le llama a una cosa por el nombre de otra), miro la cámara y veo a qué se refiere.</li><li>Cuando quiere que le ponga el fútbol, le voy indicando paso a paso qué mando de la tele debe coger (el de la tele o el del decodificador), a qué menú tiene que ir para pasar de tele a HDMI, y qué canal tiene que poner al final en el decodificador). Esto puede parecer una tontería, pero hacerlo sin ver lo que él hacía en pantalla, era muy difícil. Llegué a estar 30 minutos al teléfono para conseguir ponerlo sin las cámaras. Ahora lo hago en 1 minuto o 2, a lo sumo. Hay que tener en cuenta que él no entiende los botones de los mandos, si le dices “dale hacia arriba” no sabe qué le quieres decir, y cuando le da, a veces no apunta a la tele y no llega al menú donde debería estar (en tu plan formado en tu cabeza).</li></ul><h4>Siri y los atajos de iOS al rescate</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuvMjJSgjcyVDGL56fDvzw.jpeg" /><figcaption>Crear una lista de Favoritos para llamar</figcaption></figure><p>El <strong>cuarto problema</strong>, empezó a ocurrir hace poco tiempo: ya no entiende cómo funciona la agenda del iPhone. Sabe que allí están todos sus amigos, pero no sabe cómo usarla para llamar a ninguno (que, básicamente, es pulsar en el nombre y luego en el icono de llamar o sobre el número de teléfono). Mi primera opción fue añadir un <em>Atajo</em> con los favoritos para que solo tuviese que pulsar sobre “<em>Marcación rápida</em>” y luego la persona, y que ya llamase. Funcionó, pero lo limitaba a llamar solo a las personas de esa lista.</p><p>Finalmente, me di cuenta de que yo usaba mucho la opción de “<em>Oye Siri, llama a papá</em>”, así que le enseñé a llamar con Siri. Funcionó la primera tarde, al día siguiente ya no se acordaba, así que le pegué por detrás del teléfono una etiqueta con la frase “Oye Siri, llama a …” y así conseguí que llame siempre con Siri. Ahora sabe que puede llamar a cualquier nombre de la agenda, por lo que “…llama a Carlos” o “…llama a María” le permite llamar a sus amigos sin tener que usar la agenda para nada.</p><p>Finalmente, el <strong>quinto problema</strong>, el tema de las pastillas diarias que toma, unas por la mañana y otras por la noche, y que al principio lo llevaba perfectamente, acabó también por complicarse. Ya no sabe cuáles tocan cuándo, incluso aunque esté escrito en un papel: “por la mañana: tal y tal, por la noche, cual y cual”. Demasiadas instrucciones a procesar él solo y se bloquea. La solución obvia es que me llamaba todos los días para preguntarme, al levantarse y al terminar de cenar. El único problema era que, si yo no estaba localizable por algún motivo, se ponía nervioso.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*lSzfxNwTOVxIaJvssBocZw.png" /><figcaption>Atajo para indicar las pastillas</figcaption></figure><p>Recordé entonces el tema de los <em>Atajos </em>de iOS, nuevamente: es posible programar casi cualquier cosa con <em>Atajos</em>. Así pues, me puse a ver cómo podía hacer un atajo que, bien fuese por la mañana (antes de las 12), o por la noche, le indicase las pastillas correctas a tomar. Luego, solo había que darle como nombre algo que Siri pueda entender para que se ejecute. Y así fue: “<em>Oye Siri, que pastillas tengo que tomar</em>”. Desde ese momento, y para asombro de mi padre (tuve que convencerlo de que esa “máquina” nunca se va a equivocar y le va a decir siempre lo mismo que yo), cada vez que le pregunta al teléfono, le dice correctamente lo que tiene que tomar. La frase, obviamente, la tiene escrita en un papel.</p><h3>Conclusiones</h3><p>La tecnología te puede ayudar mucho con estas situaciones. Es posible que, en el ecosistema de Google en Android, se pudiese hacer lo mismo (o casi, los Atajos de iOS son una maravilla al estar integrados con Siri, de forma que mi padre no tiene que interactuar con un interfaz gráfico, sino simplemente hablar), pero desde luego el tenerlo todo integrado entre mi iPhone y el suyo (buscar a mi padre, sus cosas con <em>Tile</em>, aunque también podría estar usando los <em>Airtags</em>, pero ya tenía los <em>Tile </em>de antes) y que tenga Siri siempre a mano le está facilitando su vida como persona autónoma.</p><p>Estiraremos esa autonomía tanto como podamos, mientras sea seguro. Él está contento de seguir siendo autónomo, dentro de sus posibilidades. De no sentirse una carga para nadie, de poder hacer cosas por sí mismo.</p><p>Y eso es muy importante porque, en cuanto deje de hacer cosas, esa parte de su cerebro desaparecerá para no volver. Por eso, y así me lo transmiten también sus médicos, es importante que estiremos su autonomía tanto como sea posible.</p><p>Finalmente, el coste de la tecnología que he empleado, por si a alguien le sirve como referencia, es el siguiente:</p><ul><li><strong>iPhone 6S</strong> de segunda mano pero con garantía de 2 años: 120€</li><li>Dos <strong>dispositivos Tile</strong>: 20€ cada uno.</li><li>Cuatro <strong>cámaras de vigilancia</strong>: 50€ cada una.</li></ul><p>En total, 360€ en dispositivos. Es poco, muy poco, en comparación con la ayuda que me están suponiendo.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73a48dbb67fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple Login&Auth project with Slim Framework 4]]></title>
            <link>https://mcvendrell.medium.com/a-simple-login-auth-project-with-slim-framework-4-29f73d4e1d55?source=rss-f23518ec3fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/29f73d4e1d55</guid>
            <category><![CDATA[slim-framework]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[slim]]></category>
            <dc:creator><![CDATA[Manuel Conde]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 11:02:36 GMT</pubDate>
            <atom:updated>2022-02-15T11:02:36.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*6IrZ0ZsyTjuRvDIYB5ke5w.png" /></figure><p>Usually, when you want to develop a simple project in PHP, you have two options: vanilla PHP or use a framework.</p><p>I’m not a PHP dev, but do some little projects sometimes. Seems that the most popular framework for PHP is Laravel. I took a crash course on Laravel and it’s really great, but maybe overkill for a small project.</p><p>So I googled for more lighter frameworks and I found Slim Framework. It sounded good, so I studied it a bit and did my first project.</p><p>I may be wrong, but it feels like a mini-Laravel. It’s simple, but has some strong and complex concepts.</p><p>My needs where simple in this project: a login page and some protected forms to read/save data. when searching for examples, I notice that there are few login&amp;auth examples, and those I found were complex (more than I was looking for). So I decide to share my final solution, because it works and it is simple.</p><p>All the basic code to bootstrap the login&amp;auth project can be found in <a href="https://github.com/mcvendrell/SlimFramework4LoginAuth">https://github.com/mcvendrell/SlimFramework4LoginAuth</a></p><p><strong>NOTE</strong>: <em>I didn’t protect the password in the database, everything is in clear text for the shake of simplicity. In a real project you always need to encrypt passwords. Even, if possible, all sensible fields such as emails, names, etc.</em></p><h4>The basic concepts</h4><p>I decided, in order to not to complicate the project, to use PHP session to check for an authenticated user, and to use a middleware in Slim to check for valid routes.</p><p>The basic idea is:</p><ul><li>Get current session, if it exists, and check if it is valid (I set a timeout of 5 minutes).</li><li>Check if the user is authenticated or if the current route is allowed to be used without auth. If not, redirect to the login page.</li><li>Any other case, the app works as usual: App tries to get the route, the route has a controller, the controller uses a model to retrieve data and a response is made.</li></ul><p>Very simple. This little code does the auth validation trick. It is a middleware (a piece of code that is executed on every http before/after the the App code) that intercepts http request and validates all the needs to continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxInE0cqKDd9kv87FYXFEQ.png" /></figure><p>The key part is the line $publicRoutesArray = array(&#39;root&#39;, &#39;apiLogin&#39;); where you define the routes that are allowed to be navigated without auth.</p><p>The other key part is in the <em>LoginController</em>, where the user/pass is checked and the session is saved (or killed) if all is right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*dOsTaZokA0Dfu98oC-MJVA.png" /></figure><p>I think the skeleton is simple enough to be followed by anyone, and code has a lot of comments, but if you have any question, feel free to ask. From this base code, you can complicate things as much as you want.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29f73d4e1d55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Actualizarte sin consumir tu tiempo libre]]></title>
            <link>https://mcvendrell.medium.com/actualizarte-sin-consumir-tu-tiempo-libre-7bbdeebef016?source=rss-f23518ec3fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bbdeebef016</guid>
            <category><![CDATA[empresa]]></category>
            <category><![CDATA[aprender]]></category>
            <category><![CDATA[tiempo]]></category>
            <category><![CDATA[actualizar]]></category>
            <dc:creator><![CDATA[Manuel Conde]]></dc:creator>
            <pubDate>Tue, 27 Jul 2021 16:05:30 GMT</pubDate>
            <atom:updated>2021-07-27T16:05:30.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*zPuuJqOkXuZI0b01-FoeJw.jpeg" /></figure><p>Hola a todos. Tras leer el gran <a href="https://us2.campaign-archive.com/?u=374c664073e1a1fa3deca53b4&amp;id=507c46d4e7">artículo de Cynthia Gálvez en la Bonilista nº 537</a>, me he animado a escribir esto, por si a alguien le pueda interesar.</p><p>Si, como yo, llevas más de 20 años trabajando en el sector, puede que te haya pasado una de estas dos cosas: eres de los que se mantienen en la misma empresa durante mucho tiempo o eres de los que saltan con frecuencia, buscando “lo que sea” que buscas.</p><p>Yo soy de los primeros, no porque no me guste lo segundo, sino porque considero que la empresa donde trabajas es parte de tu vida, porque pasarás más tiempo en ella que haciendo muchas otras cosas. Y me gusta que mi vida sea estable, respetuosa y de confianza, por lo que, si conecto de la misma forma con la empresa que me contrata, es difícil que me cambie.</p><p>El problema clásico con esta forma de vivir es que, si la empresa es pequeña (ergo, pocos recursos) o de producto muy específico, no saldrás de un espacio muy reducido de tecnologías y de problemas a resolver: estarás muy especializado en algo muy concreto. Esto no es malo ni bueno per sé, pero si el día de mañana, tras muchos años en tu empresa, necesitas salir a buscar trabajo, es una gran limitación.</p><p>Por lo tanto, parece obvio que cualquiera en esta situación lo que debería hacer, bien sea por gusto o por necesidad, es estar al día, si es que eso es posible 🤔… no, no lo es, reformulemos la frase. Lo que debería hacer es buscar áreas nuevas de trabajo, aprender cosas que en su trabajo no vería nunca pero que le resulten interesantes (porque aprender algo que no te interesa es harto difícil).</p><h4><strong>¿Qué aprender?</strong></h4><p>Nuestro mercado es tan grande, pero tanto, que es prácticamente imposible no encontrar un área que no te llame por alguna circunstancia: desde lo más clásico de los tiempos (programas de “gestión”) hasta lo más puntero (la IA está para quedarse) hay un abanico que, si te lo pones a pensar alguna vez, es casi infinito.</p><p>Allá donde haya una secuencia de acciones, se puede aplicar un proceso y, por tanto, se puede informatizar. Es decir, que desde caminar (un exoesqueleto, por ejemplo) hasta pilotar una nave espacial se puede hacer desde la informática. Si de verdad no encuentras algo que te motive para aprender, salir de tu empresa debería ser la menor de tus preocupaciones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*J9Y6fayOrxk5jToSyXLsRw.jpeg" /></figure><p>En mi caso, soy un amante de la gestión. Cuando veo que la gente está realizando los mismos procesos una y otra vez, consumiendo su tiempo con algo que se podría automatizar y que reduciría su trabajo en un alto porcentaje, siento la necesidad de indicarlo y explicar que eso se podría mejorar haciendo “esto y aquello”. Así que, a pesar de que mis comienzos profesionales fuesen con Oracle y Visual Basic (el bueno, el clásico, no el .NET) hacia el año 97, y de que lleve en “mi” empresa ya 20 años (pasado cierto tiempo, ya la consideras tuya), una empresa dedicada a su producto y nada más, he ido probando cosas nuevas en todo este tiempo y desarrollando mis propios proyectos paralelos (“side-projects” o “pet-projects” que le llaman ahora). Eso me ha llevado a aprender diversos lenguajes, frameworks y formas de trabajar una misma idea hasta el punto en que he pasado de ser una persona de un producto, una base de datos y un lenguaje únicos a un “Fullstack developer” en lo que haga falta, siempre que eso resuelva algún proceso y facilite la tarea al que lo usa.</p><p>Pero para aprender hace falta tiempo y, ahí es donde quería llegar.</p><h4><strong>¿Cuándo aprender?</strong></h4><p>Bueno, ya he explicado que he aprendido muchas cosas en estos últimos 25 años, pero la inversión en tiempo que ha sido necesaria también ha sido enorme.</p><p>Cuando eres joven y sin compromisos, tienes todo el tiempo del mundo para aprender (las ganas las doy por supuestas). Es cierto que aprendí muchas cosas aprovechando esas circunstancias, desde casa, metiendo horas a cascoporro, incluso algún año gastando todas mis vacaciones por lanzar una idea que tenía en mente (ejem, <a href="https://www.todostartups.com/bloggers/experiencia-idolium-com-dedica-unas-palabras-a-tus-artistas-favoritos-desde-internet">Idolium</a>, ejem, fracaso total). Pero un día te casas, tienes hijos y, de repente, el 95% (<a href="https://media.giphy.com/media/3o8dFHaKKXaCxosgw0/giphy.gif">estudio de la Universidad de Kanfor</a>) de tu tiempo libre desaparece. La excusa perfecta para dejarte llevar y no aprender nada más, ¿verdad? “<em>Si es que no tengo tiempo</em>…”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*BLycon_EToPmFLbGCwONZQ.jpeg" /></figure><p>Bueno, la única solución que yo encontré a esto fue la formación en el propio trabajo. Vale, no en todas las empresas será posible, pero como comenté, la relación con mi empresa es algo primordial para mí. La empresa es parte de mi vida y, en mi vida, también quiero actualizarme. Por mi propio bien, pero también por el bien de la empresa. <a href="https://twitter.com/david_bonilla">David Bonilla</a> no para de decirlo siempre que puede y no puedo estar más de acuerdo: en nuestro sector, un trabajador contento es un activo muy productivo para la empresa, un trabajador disgustado es un problema que, tarde o temprano, acabará huyendo. Pero al margen de lo contento que esté por poderse formar, nunca sabes cuándo esa formación podrá ser usada en tu propia empresa. Con el aprendizaje también llegan formas diferentes de ver las cosas y eso podría suponer mejoras en el producto de la empresa.</p><p>Sé que algunas empresas ya incluyen horas de formación en sus contratos directamente, lo cuál me parece maravilloso. Pero si ya estás en una empresa desde hace mucho, es muy probable que eso no pase. Si tienes alguna capacidad de decisión, como es mi caso actual, puedes “dictar” una nueva norma que permita cogerse unas horas al mes para formación (idealmente, los viernes si no hay ningún “incendio” que apagar, el ánimo suele estar alto por llegar el finde y aprendes con más ganas, incluso si te “enganchas” y se te quedado algo pendiente puedes buscar tiempo durante el finde). Si no eres el que manda, yo hablaría con el que manda para intentar algo así. Lo máximo que te puede decir es que no. ¿Pero y si sí?</p><h4><strong>¿Y si no quiero aprender?</strong></h4><p>Bueno, tampoco se acaba el mundo. Conozco mucha gente que no aprende nunca nada, no tiene interés más que en realizar su función actual correctamente y nada más.</p><p>No es ningún problema mientras la empresa siga en pie y contando contigo. Lo malo es si alguna de esas dos cosas falla. En un país con “pleno empleo” tampoco debería ser un problema: si sabes hacer tu trabajo, buscas otro y listo. Pero en los tiempos que corren, estamos lejos del pleno empleo (siendo nuestro sector privilegiado, con altísima demanda) y el mercado evoluciona muy rápido. Quizá la que era tu función ya no sea un perfil muy buscado y tengas problemas para encontrar otro empleo.</p><p>No sé, yo solo le veo ventajas al aprendizaje, sobre todo si te dejan hacerlo en tu trabajo. ¿Tú no?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bbdeebef016" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>