teleren/devto huggingface dataset:
Create an ESP32 based smart device with Arduino and MQTT
Tags: esp32, mqtt, arduino, smartdevice
Published: 2022-01-06 22:16:50

---
title: Create an ESP32 based smart device with Arduino and MQTT
published: true
description: Getting started with ESP32, Arduino and MQTT
tags: #esp32 #mqtt #arduino #smartdevice
//cover_image: https://direct_url_to_image.jpg
---

# Introduction
This article will show you how to quickly create an ESP32 based "smart device", using Arduino, by creating a simple application that basically connects your WiFi router, then a MQTT server, and publishes a message every five seconds.

Of course, you can use any other WiFi enabled board.
I chose the ESP32 because I recently bought a LiliGo TTGO ESP32 board, without any specific project in mind.
This is the board I use: http://www.lilygo.cn/prod_view.aspx?Id=1126

# Configuration
## Board
First, we need to add support to our ESP32 board.
* In the Arduino preferences, in the *Additional Boards Manager URLs* field, add: `https://dl.espressif.com/dl/package_esp32_index.json`
* In the **Tools** menu, open the **Boards Manager** and look for *esp32*, then install it.
* Still in the **Tools** menu, choose your board (*TTGO LoRa32-OLED V1* in my case)

## Libraries
* In the **Sketch** menu, select **Manage Libraries...**
* Install library *PubSubClient*

# Code
## Configuration
### Headers
```
#include <WiFi.h>
#include <PubSubClient.h>
```
### Definitions
Let's define our WiFi SSID, password, and the MQTT server
informations (hostname, port, username, password, client).
```
#define ssid          "MyWiFi" 
#define password      "MyWifiPassword"
#define mqtt_host     "MyMQTTServer"
#define mqtt_port     1883
#define mqtt_client   "ArduinoCl"
#define mqtt_user     "julzor"
#define mqtt_password "SomePassword"
```
### Global variables
```
WiFiClient espClient;
PubSubClient cli = PubSubClient(espClient);
```
## Connecting to WiFi
```
void setup_wifi()
{
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
  }
}
```
## Connecting to MQTT
```
void setup_mqtt()
{
  cli.setServer(mqtt_host, mqtt_port);

  if (cli.connect(mqtt_client, mqtt_user, mqtt_password))
  {
    // Now we're connected to the MQTT server
    // Let's publish a first message...
    cli.publish("test/hello", "hello world");
  }
}
```
## Putting it all together
### Setup
```
void setup()
{
    Serial.begin(115200);

    delay(10);

    setup_wifi();
    setup_mqtt();
}
```
### Loop
```
long last = 0;

void loop() {
  if (!cli.connected())
  {
    // We were disconnected, let's reconnect
    delay(1000);
    setup_mqtt();
  }
  else
  {
    cli.loop();

    long now = millis();
    if (now - last > 5000)
    {
      last = now;
      cli.publish("test/ping", "Ping");
    }
  }
}
```

# Conclusion
You should now have a working application that does nothing but send a ping message on your MQTT server. That's a start!

In another article, I will show you how I use my useless smart device with Node-RED, a Raspberry Pi, and Alexa.
Setup RSpec on a fresh Rails 7 project
Tags: rails, rspec, testing, ruby
Published: 2022-01-06 22:13:32

_Photo by <a href="https://unsplash.com/@jonathanbean?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Jonathan Bean</a> on <a href="https://unsplash.com/s/photos/blacksmith?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>_
  

Installing RSpec, FactoryBot, Faker gems and configuring for testing environment. 

*Using Ruby 3.0.1 + Rails 7.0.0 at the time of writing this article*

Let's get right to it...

## Start a fresh project

```
rails new projectname -d postgresql
cd projectname
git add -A
git commit -m "initial commit"

rails db:create
rails s
```

## Install gems

```
git checkout -b rspec
```

In Gemfile add...

```
group :development, :test do
  # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
  gem "debug", platforms: %i[ mri mingw x64_mingw ]
  gem "rspec-rails"
  gem "factory_bot_rails"
  gem "faker"
end
```

Back in terminal/command line...

```
bundle install
rails g rspec:install
```

## Configure gems

Create 'support' directory in 'spec' directory and create two files

```
spec/support/factory_bot.rb
spec/support/chrome.rb
```

And then one file in the spec directory for factories.

```
spec/factories.rb
```

Configure FactoryBot

```
# spec/support/factory_bot.rb

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end
```

Configure driver

```
# spec/support/chrome.rb

RSpec.configure do |config|
  config.before(:each, type: :system) do
    if ENV["SHOW_BROWSER"] == "true"
      driven_by :selenium_chrome
    else
      driven_by :selenium, using: :headless_chrome, screen_size: [1400, 1400]
    end
  end
end
```

Require support files in `rails_helper.rb`

```
# spec/rails_helper.rb

require_relative 'support/factory_bot'
require_relative 'support/chrome'
```

When you generate a User model (or any model) RSpec will generate a factory for you in your `factories.rb` file.
You can modify it to look like this.

```
# spec/factories.rb

FactoryBot.define do
  factory(:user) do
    email { Faker::Internet.email }
    password { Faker::Internet.password }
  end
end
```

## it "should run a test" do...

Run `rspec` command in the terminal and you should see it run and output some green text.

```
-> rspec
No examples found.

Finished in 0.00038 seconds (files took 0.94577 seconds to load)
0 examples, 0 failures
```

## Finish up

```
git add -A
git commit -m "add rspec"
git checkout main
git merge rspec
git branch -D rspec
git push # assuming you have a repo online somewhere
```
My All Time Favourite TV Series List
Published: 2022-01-06 22:01:15

I've been wanting to list my all time favourite tv series for some time in case someone and is looking for something new to watch (there are some absolute Gems in this list).

I've stopped short of categorising them by genre, noting the # of series etc but I might do in future..

If you feel the need to pull this list apart or be negative about it - I'd recommend you take a good look in the mirror. This is solely my opinion, you may have yours.

These are in ROUGH order - it's quite hard to maintain a rank when it gets so long and adding new items.

You may find there are some glaringly obvious omissions from this list - It's probably just because I haven't watched them (i'm not claiming to be a TV series expert).

I hope you find the list useful. I will probably continue to alter and update it over time.

** = A lesser known (but awesome series)

- The Witcher
- Mandalorian
- Ragnarok*
- Loki
- The 100
- The Expanse
- Boba Fett
- Babylon 5
- Person of Interest*
- Star Gate
- Arrow
- Revolution
- Star Gate Atlantis
- Agents of S.H.I.E.L.D
- Battlestar Galactica
- Big Bang Theory
- Travelers*
- Salvation*
- Star Trek Discovery
- Ascension*
- Stranger Things
- Lost In Space
- Eureka
- Warehouse 13
- Terra Nova*
- Falcon and the Winter Soldier
- Star Trek Lower Decks
- Caprica
- Picard
- Another Life
- The Umbrella Academy
- The Man in the High Castle
- Cobra Kai
- Vigil
- Pine Gap
- Smallville
- Stargate Universe
- Homeland
- The Flash
- 4400
- Fringe
- Heroes
- Firefly
- Hawkeye
- Andromeda
- Travels with My Father
- Helix
- Defiance*
- Space Force
- Luke Cage
- Marco Polo
- Elementary
- Sherlock
- Scorpion*
- Mr Robot
- The IT Crowd
- Star Wars Clone Wars
- Star Wars Rebels
- Farscape
- Defenders
- Daredevil
- Away
- Suits
- Breaking Bad
- Sanctuary
- The Walking Dead
- Jessica Jones
- The OA
- Tiger King
- Iron Fist
- You
Problema na instalacao do MySql
Problem installing MySql
Tags: mysql
Published: 2022-01-06 21:58:08

When I go to install my mysql, it hangs in the following installation screen, what to do? I've already looked for more unsuccessful solutions

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pjzqloqn4y0iyrhwe2mv.png)
Star Rating Part 1
Tags: html, javascript, css
Published: 2022-01-06 21:26:29

---
series: Start Rating
---
I am creating multipart series about creating a star rating using html, javascript and css.

{% codepen https://codepen.io/Mrlallu/pen/QWqByVw %}
I am using a custom element called `custom-rating`.

So what do you think about my approach ?

- Referece 1: https://developers.google.com/web/fundamentals/web-components/customelements
- References 2: https://developers.google.com/web/fundamentals/web-components/customelements#attrchanges
These were my favorite apps of 2021
Tags: software, apps, beginners, productivity
Published: 2022-01-06 21:15:47

This is not some kind of paid promotion. Just that sometimes are curious about what other people use in a daily basis.

When I ask, I get different responses and is cool to have this variety.

So I present my favorite apps/software of the last year

## My favorite apps

### Calm

A sleep and meditation app, has a ton of meditation exercises and calm music. Really an amazing app , i wish it has a better web app but for now it’s ok.

### Dashlane

This password manager is really useful. By now it makes all that it needs to do. Also it has VPN, and a dark web email analyzer. It is a really great password manager.

### Toggl

It is a time tracker useful when working on different projects and clients. For me i use it to know how many time i spent on different topics.

### Rescuetime

Another time tracker, this really blows my mind. It can track without specifying some task. When i open my PC it begins to track, really useful.

### OS: Ubuntu

This was the year i began to use linux. Ubuntu has make things easier in development, although i had audio related issues, and the os freeze sometimes.

## Let's connnect
Remember you can follow me on Twitter @fernandocutire, I am getting better at writing in English so we could talk there
4 years of taking online education taught me this (first year) Pt1
Tags: productivity, career, opensource, beginners
Published: 2022-01-06 20:51:57

Online courses are everywhere, and every day there are more. 
This is not going anywhere, and don't expect that it would slow down.

In a series of articles, I will explain my approach to online education. 

This is written in a personal way, maybe you can relate. It wasn't always perfect, I was really slow and the start.

# So this was the first year.

In my first year, I discover online courses, but I didn’t see it as a way that can help me at the time. 

I would only say to myself, this looks good but I don’t feel pressured to finish it, maybe someday, like when I am looking for a job I will have better reasons

As you may know, my way of thinking was not very mature, and it wasn’t because I was at school with so many hours and for me, it was not a big deal to finish.

The topics that interested me at the time were mainly programming and business. I enroll in 3 free udemy courses and paid for 3. I remember that I just completed 2 but because it was 2 hours or less, so no big deal.

As you may know, some Udemy Courses can get through 30 hours of content, and this makes it hard to finish. At the time I thought that more content meant that the course was better, but obviously, I was mistaken.

Finally, it is important to say that I just took courses from Spanish speakers instructors so as you may think, the offer was not very high back then.

This series will continue.

## Let's connnect

Remember you can follow me on Twitter  [@fernandocutire](https://twitter.com/fernandocutire
), I am getting better at writing in English so we could talk there
100 Days of Learning - Day 5
Tags: 100daysofcode, codenewbie, sql
Published: 2022-01-06 20:46:22

---
series: 100 Days of Learning
---

Hello and welcome to my 100 Days of Learning challenge! As I mentioned yesterday, I'm starting to dig deeper into SQL for work. I found a course on Pluralsight that has been so helpful and really changed how I think about my SQL queries (link below).

## My Learning Goals for today:
- complete the Pluralsight course on [SQL Queries](https://app.pluralsight.com/courses/3f251961-754f-4d57-9e35-0eada434a7c0/table-of-contents)

## What I Completed:
- I finished the course!

## What I Learned:
Finishing out this course covered FROM, WHERE, GROUP BY, and HAVING clauses, and so much more. The examples in this course are so thorough and explain why different errors might occur in your queries (and really drill in execution order). I plan to revisit these and start to put together a series on SQL based on what I've learned.

I also signed up for [CodeNewbie's 2022 Learn In Public Challenge](https://dev.to/devteam/the-codenewbie-challenge-is-returning-for-2022-with-exciting-new-updates-2b32), so maybe this SQL series will be my focus for that. It's about a month away, so we'll see if I've moved onto learning something different by  then.

## My Goals for Next Time:
- Start the Pluralsight course on [SQL Joins](https://app.pluralsight.com/library/courses/combining-filtering-data-tsql)
 - When I finish these Pluralsight courses, I'm going to do a case study of the queries I've been using at work in my day-to-day, and then ask my developer to give me a deep dive on how the DB for one of our main projects is structured.

Thanks for joining me on this journey. If you're doing your own #100daysofcode, please share in the comments! I'd love to hear about what you're learning.
Rendering: Half-Full or Half-Empty?
Tags: javascript, beginners, flatiron, todayilearned
Published: 2022-01-06 20:41:21

Today I was working on a lab for my Flatiron courses and noticed a note:

> "Pessimistic rendering is recommended."

Well what the heck does that mean? Is my program feeling low? Down? Defeated? (Sometimes I do when I hit a snag, but that's no reason for the program to feel that way...)

I quickly learned that there are two different forms of rendering:

- Pessimistic
- Optimistic


In today's world of instant gratification, users generally don't want to wait for anything to load. It's understandable - with fast internet and apps that are designed for delivering information fast, we've just gotten used to it. When you are coding, it's smart to keep this in mind, because often you will discover changes you can make that will update your DOM but won't necessarily require you to reload/refresh your entire page. This kind of rendering is referred to as Optimistic, because it assumes that the server will update the database with the new information and doesn't depend on having to go through another load and fetch and render to display the new information. It simply says, 'oh, I see that you like this. I trust my program will update the database for you, so I'll just mark down your like really quick so you can continue browsing."

On the flip side, the pessimistic way of rendering these changes involves the rigmarole of sending a patch, reloading the page, fetching the new data, rendering everything all over again... it's not very trusting of your program and though it might not take a very long time, any time spent reloading might allow the user a moment to turn their attention elsewhere.


Optimistic rendering is obviously more desirable if you're trying to keep the user's attention on your program, but there are pros and cons to each style. Optimistic approaches work best with pretty simple tasks - tasks like "liking" things. When you get into more complicated tasks, like filling out forms or making a purchase, that's when you need the functionality of pessimistic rendering. It will be more accurate and dependable than making a visual change and hoping that it saved in the back-end.
O Ciclo Formativo PretaLab e o que aprendi sobre comunidades em tecnologia
Published: 2022-01-06 20:35:36

O II Ciclo Formativo em Tecnologia do [PretaLab](https://www.pretalab.com/), iniciativa da organização [Olabi](https://www.olabi.org.br/), acabou faz algumas semanas e foi uma das melhores experiências que vivi em 2021. O Ciclo conta com três grandes frentes de atuação: autoconhecimento, conhecimento técnico e autogestão. Todas as atividades dos eixos são paralelas, complementares e ficam distribuídas ao longo de três meses.

Vou compartilhar as principais coisas que vivi no neste período do ciclo:

**- Reconhecer as próprias fraquezas**
Não é nada fácil olhar pra nossas fragilidades. Mas, em muitos casos, é assim que a gente pode encontrar algumas respostas pra dificuldades na carreira. Fazer parte de alguma comunidade é essencial para perceber no outro fragilidades que a gente tem e de fato poder transformá-las.

**- Aprender dói e não tem atalho**
Eu me vi em vários encontros com bastante dificuldade, como se houvesse um muro pra ser atravessado. E é nessa fase do “será que eu consigo aprender?” é que a gente encara algo que precisa ser construído.

**- Aprender sozinha é possível, o problema é que dói muito mais**
Por vários momentos ao longo da minha jornada na tecnologia eu fiz do jeito mais difícil: completamente sozinha (“sozinha” que menciono aqui significa sem trocar com outras pessoas porque o aprendizado precisa ser tirado de um material que outra pessoa produziu). Mas sempre é bom perguntar pra quem já fez aquele caminho antes. Sem perguntar a ninguém ou ter uma conversa curta, você pode encontrar respostas, mas será muito duro e lento.

**- Procure a sua turma o quanto antes (agora é uma boa hora!)**
Sempre há pessoas com quem a gente pode trocar, com quem a gente se identifica. Acho que aqui posso dar algumas dicas de como começar: Se você faz universidade, entre nos grupos e interaja com os colegas; A linguagem que você está estudando ou tem interesse tem grupo no Telegram. Procure-o e entre pra acompanhar as discussões; Tenha Twitter, siga as pessoas atuantes na comunidade e acompanhe as conversas; Participe de capacitações em comunidades que você se identifica pra conhecer pessoas. Assim, as chances são maiores pra um aprendizado mais assertivo.

**- Seja autocrítica, mas cuidado pra não ser rigorosa demais!**
A troca faz a gente ouvir de outras pessoas sobre o nosso trabalho. Muitas vezes a gente sabe mais do que imagina, mas a auto cobrança entra como fator que pode sabotar a aprendizagem.

**- Pedir ajuda é parte do crescimento**
O maior legado do Ciclo foi a oportunidade de conhecer pessoas incríveis com quem posso contar e aprender. Aprendi a pedir ajuda e sempre que precisei fui muito apoiada.
WeAreDevelopers Live - Java Day
Tags: java, wearedevs, developerevent, onlineevent
Published: 2022-01-06 19:31:20

Ready to level up your Java skills? Then sign up and join for our first WeAreDevelopers Live Event this year - it’s Java Day! **It’s free!**

When you think about Java you either think about beautiful tropical islands, a good cup of coffee or that’s right: one of the best known and most important programming languages of all time. Basically there’s nothing you can’t do with Java- therefore we have reached out to some real Java Pros to learn what’s on their mind!

So grab your coffee and tune in on January :

👉🏻 **Going reactive with Spring WebFlux**
📣 Michael Eder & Philipp Frauenthaler

👉🏻 **Get old, go slow, write code!**
📣 Tobias Modig

👉🏻 **What´s New for Developers Moving from Java 11 to 17?**
📣 Daniel Strmečki

👉🏻 **The Cool Thing about Cool Things in Java 16 & 17 LTS**
📣 Mohamed Taman

Save your spot - **it's free**! 
https://bit.ly/WADJavaDay2021


PS: Join our latest **raffle** provided by Deloitte for your chance to **win a Nintendo Switch** and some **nice goodies**. https://bit.ly/WADWinaNintendoSwitch
Clearing Rows with CSS Grid
Tags: html, css
Published: 2022-01-06 19:14:26

Today I completed a fun little challenge using CSS Grid.

The goal was to update a layout that relied on container elements and flexbox.

```html
<div class="cards">
  <pfe-card id="a-1">...</pfe-card>
  <pfe-card id="a-2">...</pfe-card>
  <pfe-card id="a-3">...</pfe-card>
  <pfe-card id="a-4">...</pfe-card>
</div>
<div class="cards">
  <pfe-card id="b-1">...</pfe-card>
  <pfe-card id="b-2">...</pfe-card>
  <pfe-card id="b-3">...</pfe-card>
  <pfe-card id="b-4">...</pfe-card>
</div>
```
```css
.cards {
  display: flex;
  flex-flow: row wrap;
}

.cards > * {
  margin-bottom: 15px;
  margin-right: 15px;
  min-width: 200px;
  width: calc(25% - 32px);
}
```

My first step was to remove the container elements and 'lift up' the flex properties into the grid container

```html
<pfe-card id="a-1">...</pfe-card>
<pfe-card id="a-2">...</pfe-card>
<pfe-card id="a-3">...</pfe-card>
<pfe-card id="a-4">...</pfe-card>
<pfe-card id="b-1">...</pfe-card>
<pfe-card id="b-2">...</pfe-card>
<pfe-card id="b-3">...</pfe-card>
<pfe-card id="b-4">...</pfe-card>
```
```css
:host {
  display: grid;
  grid-template-columns: repeat(
    auto-fill,
    minmax(
      200px,
      calc(25% - 32px)));
  grid-auto-rows: max-content;
  gap: 15px;
}
```

This did most of the job on its own, but there was one issue: in the original layout, card `b-1` appeared in a new 'row' below the first set of cards. How could I emulate this 'row-clearing' behaviour? Using `grid-column`, I specified the position of the first card in the second set:

```css
#b-1 {
  grid-column: 1/2;
}
```

Now, that one specific card 'resets' it's whole row, replicating the original behaviour, but with fewer non-semantic elements, and less CSS.


![Browser Screenshot showing rows of cards. The second row ends with two empty cells, and the third row begins with the desired element](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xwu3aivsmjqa0g898mbj.png)

_nice_
React folder structuring
Tags: react, webdev, architecture, programming
Published: 2022-01-06 19:14:11

Hey all great minds, this post is all about how I used to structure the react applications that I built so far. It's completely opinionated. Please comment with your thoughts.

Let's assume that we are building a simple application with some common modules and features in it. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c4a07e7oyxeqhm72jxdl.png)

I always do the structuring based on the features or routes. This is the most common approach by the react community.

From the above project view, when we open the "src" folder, all the folders with the feature name need to be aligned on the same vertical line. By looking at these folders inside the "src" folder, we should come to an idea of the nature of the application and what this project is about.

Every features folder should contain an "index.js" file that has the root component of this feature. The presentational and non-presentational components are placed inside the "Components" folder. The other files are styles.js, actions.js, actionTypes.js, and reducers.js are placed within the folder for all the features

Every feature folder should have all these files which help in code splitting and project folders looks identical which avoids chaos and helps better debugging.

The "Common" folder can contain the styles, constants, utils and components which we think can be used by other components.
Redux without the sting
Published: 2022-01-06 19:05:19

Redux is a _"state management system"_ (English: creates one layer for data and actions to live)

Once imported you can spin up Redux by creating a _store_
`const store = Redux.createStore(reducer)`

A reducer is the brains of the operation. It takes in actions and handles the state.
`const reducer = (state=0, action) => {
/* initialise state as 0 */

  switch(action.type) {
    case "INCREMENT":
      return state + 1;
    default:
      return state;
  }
}`
Error saving your changes: Description control characters are not allowed
Tags: github
Published: 2022-01-06 18:58:18

Did you ever come across this error while adding a lovely description after doing days of hard work on your project.

**SOLUTION**

![Solution of description control characters in GitHub](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3lx70iopropy7vuh2lcy.png)

Just remove the new line and it'll save properly.