Internet Bar (Clients and Servers)

 


 

introduction

The title is certainly ironic, but I wrote it because in this article, I would like to describe without going into boring technicalities, since I would also like to address people not in the sector, or those who, moved by curiosity, want to gain some experience in the sector of "digital information management", "young students" or "old hobbyists", who use the internet, also to learn something that they have not had the opportunity to delve into in their cultural journey.

A chat "at the Internet Bar", among friends in short, just to spend some time together, in front of a good glass, watching the "Bits" passing by on the street.

Yes, the Internet could be just like an immense metropolis, full of busy roads, avenues, alleys, streets and alleys, which lead to houses, condominiums, buildings and skyscrapers full of apartments, offices, shops, restaurants and bars, various places full of attractions, museums, libraries, up to the large factories in the suburbs, all with their own specific unique address, something "Registered", which identifies, in the simplest possible way, that particular "house number", to which the data flows, composed precisely of bits, but which can also be "dynamically configured", to respect the dynamics of such an immense metropolis, always evolving.

 

IP addresses

An IP (Internet Protocol) address is therefore a unique numerical label assigned to each "device" connected to the Internet's communication channels.

This address serves two main functions: identifying the “device” and locating it.

IP addresses are therefore like postal addresses, which allow data packets to find the right destination (street and house number), and also the person to whom they are intended.

The birth of an "internet protocol" occurred in 1981 with the publication of RFC ("Request for Comments") 791, a fundamental document that defines the IP network protocol, developed by the IETF (Internet Engineering Task Force) and uses 32-bit addresses, represented by four decimal numbers separated by dots (e.g. 192.168.1.1), which allowed approximately 4.3 billion unique addresses, which for the time, seemed very many, but, given the technological evolution and rapid growth of the Internet, it became necessary to adopt the successor, IPv6, starting from the end of the 1990s.

IPv6 was officially born as a standard in 1998 to solve the IP address exhaustion crisis, but its practical introduction was gradual, with the first tunnel in Italy in 1999 and implementation on "root servers" in 2004, marking the beginning of the era of greater address availability for the Internet.

IPv6 is a hexadecimal format separated by colons (e.g. 2001:db8:0:1234:0:567:8:1). We therefore go from 32bit to 128 bit, offering an almost unlimited number of addresses to support the exponential growth of connected devices (IoT, aka Internet of Things, or "Internet of Things").

 

Types of IP addresses

Public IP: the public IP address is the one assigned by the Internet service provider (ISP) and allows external devices to communicate with the public network.

Private IP: within the home network, however, the "router" assigns unique private IP addresses to each connected device (therefore each one has its own unique, private identifying IP!).

These are not visible outside the network.

Static IP: an address that does not change over time, it is useful for devices that must always be reachable, such as "servers".

Dynamic IP: An address that can change over time and is dynamically assigned to a device, for example, when connecting to a public Wi-Fi network.


 

Computer networks

The ways in which data travels are defined as "Networks", there are different types, many say that the internet can also be defined as "the network of networks", at a planetary level, an intricate system of connections, devices and circuits that serve to exchange data of all types, but always of a digital nature, something very complex that serves as a global tool to facilitate communication which is undoubtedly the most widespread activity on this planet inhabited by plants, animals, humans, machines and who knows what else, it is the generation of information, which includes its communication and interpretation, through reception processes.

As regards artefacts and humans, in recent times the most used system for communication is the digital transmission / reception of data, digital communication is based on computer networks and computer networks are composed of a set of hardware devices that use software, and are connected to each other, through certain communication channels, designed to manage the transmission / reception of data constituting the information.

 

The concept of information

In action form”, even without bothering ancient languages to derive the etymology, the breakdown of the word “information” suggests that it is something that can be used to “give shape”, something that is exchanged to be used in some way.

From the above, it can then be deduced that information is a "measurable quantity", or rather, "quantizable".

For our written communication, we use symbols, which are the "elementary particles" of a language, it therefore seems logical to think that every single particle has a computer content distinguishable from every other particle of that language.

But any information has its own meaning of existence if and only if it is at least transmitted.

We could say that, if something "exists", it cannot "not communicate", but then, the concept of information takes on meaning precisely if related to communication.

Therefore, according to the "Information Theory", in a communication, consisting of a signal correlated to a language considered as a finite set of transmissible objects with discretionary symbols, the information is associated with each transmitted symbol and is defined as the reduction of uncertainty that could be had a priori on the transmitted symbol.

In particular, the amount of information related to a symbol is defined as:

I = - log2 Pi

where Pi is the “probability” of transmission of that symbol.

The amount of information associated with a symbol is measured in bits.

The quantity of information thus defined is therefore a discrete random variable, whose average value, typically referring to the "source of symbols", is called entropy of the source, and is measured in "bits/symbol".

The entropy of the source is by definition equal to the summation, extended to all the symbols of the source, of the products between the probability of each symbol and its information content.

In particular, it can be seen from the formula that if the probability Pi of transmitting the symbol is equal to one, the amount of associated information is zero; vice versa if in the ideal limiting case of “Pi=0 the amount of information would be infinite.

From the above we can deduce the philosophical depth that this theory can take on, which evidently has much broader mathematical-physical correlations than those summarized in this exposition and which I invite you to delve deeper into, perhaps starting from the study of philosophers such as Plato and Aristotle, to perhaps arrive at the "Shannon and Weaver model", the theory of "Data Bases" and the "Relational Model".

 

Communication

The information speed of a source, which does not coincide with the frequency of emission of the symbols, given that each symbol does not necessarily carry a bit of "useful" information, is the product of the entropy of the symbols emitted by the source times the frequency of emission of such symbols (signaling speed).

One of the main problems of communication is "data coding", meaning, with this term, the potential to transform generic information into understandable information.

This operation is difficult even for humans who speak the same language, let alone implementing this ability on devices that must implement computer processing.

The first problem to address in information processing processes is the representation of information.

Information consists in the possibility of transmission and reception of a message among a set of possible messages, therefore the exact definition is that information is represented using a finite number of reliable and easily distinguishable symbols.

As regards digital equipment, information is represented by voltage levels or by magnetization of appropriate devices (mass memories, etc.).

Reliability requirements require that these symbols, for greater efficiency, be three:

  • 2 voltage levels standard example TTL: 0/5 V; RS-232 standard: +12/-12 V, which form the binary numbering; (frequency modulations, amplitude modulations, phase modulations)

  • HiZ (high impedance), which represents an indeterminate level, caused for example by the "disconnected" wire, (absence of carrier signal).


Information travels on "channels", and each channel can be attributed to a "data transmission/reception potential, which is independent of the transmission speed, but of the quantity of simultaneous transmission of the data transmitted, by analogy, think of irrigation channels, or water pipes.

A channel can consist of at least a transmitter and a receiver and a communication support.


Data communication can therefore take place in different ways:

  • simplex”, when the message is sent through a single step;

  • half duplex”, when communication occurs in both directions, but at different times;

  • full duplex”, when transmission occurs in both directions simultaneously.


It is also true that we may find ourselves faced with other situations, such as that of a teacher communicating to students, where a source communicates to many (or all those who are part of its communication network).

Or where many communicate to a single potential recipient, a much rarer case apparently for human beings, but which can be understood as a community prayer session, which instead commonly happens for automated communication systems, where many "hosts" or "clients" communicate with a "server", as in a bar!

Finally, the situation of "global communication", where everyone communicates with everyone... perhaps at the same time, yes, a utopian condition! But it presents some beautiful considerations that can be better explored in philosophical terms.

The messages, or interpretable codes, communicated and received whether they have been interpreted or not, therefore constitute the exchange material of computer networks.

There are two particular cases to consider, one concerns the source of communication, in the unfortunate event that it generates "empty" communication, where its message does not find any available receiver, and the other, an existing receiver that does not receive any message, whether it is interpretable or not!

These are extreme cases, which can be problems for animal communications, but do not constitute problems for the communications of automatons, except for the fact that, in the absence of energy supply, these would end up fulfilling their task.

A message – or code – is sent using two types of switching techniques:

  • circuit”, characterized by a stable connection between two users, for the entire duration of the communication;

  • packet”, when multiple users simultaneously send information across the network, using the same communication channel.


Computer networks in general are cataloged based on their extension and functionality.

 

The “LAN” network

English acronym for "Local Area Network", the LAN is a network that is created within limited areas in which information travels through a simple Ethernet cable or via Bluetooth or WiFi channels such as a home, or an office, a factory, or a school.

With this type of network, hardware resources such as printers or scanners, other IoT devices, or software resources are generally shared, where documents and files of any type can be managed.

The “MAN” network

English acronym for "Metropolitan Area Network", the MAN is a type of computer network that comes into play when information and data must reach greater distances and be shared within a city.

In this case, we rely on public domain networks such as, in general, the telephone network, which is capable of reaching almost all buildings and connecting different local networks, by cable, fiber, or via WiFi.

The “WAN” network

English acronym for "Wide Area Network", the WAN is a very large type of network, which includes cities, nations and entire continents, obviously connecting both LAN and MAN networks together.

Wide Area Networks are owned by a specific organization or company and are managed privately or rented, furthermore Internet Service Providers (ISPs) use WANs to connect company networks and end customers to the Internet.

With the modern complexity inherent in infrastructure evolutions, the following networks can also be defined:

Le reti “PAN” o “WPAN”

Acronimo inglese di “Personal Area Network” o “Wireless Personal Area Network”, sono piccole reti “ad och” che usufruiscono di connessioni “USB” o bluetooth.

Una Wireless Personal Area Network che funziona tramite bluetooth prende il nome di “piconet”.

Le connessioni PAN e WPAN si estendono normalmente per pochi metri e non sono quindi adatte a collegare dispositivi in stanze diverse o in altri edifici.

The “GAN” network

English acronym for "Globe Area Network", the network (GAN) should identify the global network of connections of all the "nodes". However, a network like "Internet" is not the only one of its kind.

There are companies that manage closed networks, which include several WANs and thus manage to connect their computers worldwide EXCLUSIVELY.

GANs use the fiber optic infrastructures of WANs and connect them through international submarine cables or satellite transmissions.

VPN” virtual networks

English acronym "Virtual Private Network", the VPN network is a virtual communication network that uses the infrastructure of a physical network to connect systems in an encrypted manner.

Usually it is a network that uses "Internet tunnels" as a means of transport, so as to connect computers worldwide and be available free of charge. Unlike MANs or WANs which are privately managed, data transfer takes place via a virtual encoding/decoding system, which serves to establish a connection between a VPN client and a VPN server.

The purpose of using VPNs is usually to connect several LANs to the Internet, or to make remote access to a network or a single computer possible via a public connection.

An IP address therefore constitutes the basis for the communication of information from the sender to the recipient.

In the most common sense, the network is made up of nodes, or if we want "hosts", which can be either software services or even equipment identified by an IP address, which, as described above, has two main characteristics: being public or being private and two secondary characteristics, being static or being dynamic.

N.B. The term "host" derives from the Latin root, hspettim, where it means "host", "innkeeper" (the owner of the bar!), and has evolved in the computing context to indicate a device that provides resources or services (such as a web server) to other devices or users ("guests" or "clients").

Therefore, the public IP address is an address visible and reachable by all hosts on the Internet, while the private one is used to uniquely identify a device belonging to a local network.

Dynamic addresses are the most used and are used for normal online browsing, these are usually provided by an Internet Service Provider which assigns a temporary random IP address which is changed at a pre-established interval.

Dynamic IPs guarantee greater protection of user privacy by allowing more anonymous browsing.

A static IP address, of course, remains unchanged, however the owner can request it to be changed if it is public.

Static IPs are usually used in LANs or PANs (private networks) to communicate with a printer or another computer on the local subnet.

The IP address is in turn made up of two parts: the first is a network indicator "Net_ID" and the second is the host indicator "Host_ID": the Net_ID part is assigned by ICANN (Internet Corporation for Assigned Names and Numbers), which in turn delegates regional organizations (Europe, Asia, etc.) which in turn delegate other organizations (for Italy the responsible organization is the GARR).

ICANN is responsible for assigning IP addresses and is responsible for managing the generic top-level domain (gTLD), international code (ccTLD) and GAN root server systems.


 

However, the "physical machines" that connect to the network also have another important address, which identifies their origin and function: the "MAC" address (English acronym for Media Access Control), also called physical address, Ethernet address or LAN address.

This address is a 48 bit (6 byte) code uniquely assigned by the manufacturer to every Ethernet or wireless network card produced in the world.

To make IP technology more user-friendly, some name resolution services have been implemented, i.e. which associate a readable name with a specific address, i.e. a system called "DNS", English acronym for "Domain Name System" which is a directory service used for resolving "server names" providing the correspondence between logical and textual addresses "URL", English acronym for "Uniform Resource Locator" and IP addresses.

The peculiarity of DNS is that it allows, for example a website, to be hosted on multiple servers, each with its own IP address, with a consequent division of the workload.

To conclude, each Internet node is therefore assigned a unique IP address, within a LAN, the IP addresses can be assigned manually by the network administrator (static IP) or, as usually happens, the assignment occurs automatically through a DHCP server, English acronym for "Dynamic Host Configuration Protocol", typically installed on a "Router", responsible for issuing addresses, which uses a "subnet mask" to identify the components of a private network, which once, through a "Gateway" which using the DNS system can be connected both as client and server.

Usually the gateway function is performed by the router itself.

The gateway is therefore a device or software that carries out a protocol translation between two networks, while the router is a device responsible for routing data packets across a network.

The internationally standardized communication model is called "OSI", an acronym for "Open Systems Interconnection", by the International Organization for Standardization (ISO).

The figure shows the specific functionality of the components that are used for the hardware and software management of internet connections for a small local network.

 

 

Subnet mask

A subnet mask is a 32-bit number that, in TCP/IP networks, is used to divide an IP address into two parts: the network address (network ID) and the specific device address (host ID).

This allows devices to understand whether another host is on the same local network (and therefore communicate directly) or on a remote network, forwarding the data to the gateway.

It works via a logical AND operation, identifying the network part with bits at '1' and the host part with bits at '0'.

 

What is it for:

Network/Host Identification: distinguishes which portion of the IP identifies the network and which the individual device.

Network Efficiency: divides a large network into smaller subnets (subnetting) to reduce traffic, improve security and management.

Routing: Routers use the subnet mask to determine the correct path for data packets.


How it works (in brief):

Structure: It is a 32-bit number, written as four octets (e.g. 255.255.255.0).

Bits at '1': correspond to the network part of the IP address.

Bits at '0': correspond to the host part of the IP address.



Logical AND operation: The computer does an AND operation between its IP and the subnet mask to find the network address, and a similar operation on the destination IP to compare networks.

Example: With a subnet mask of 255.255.255.0, the first three octets (255) indicate the network, while the last octet (0) identifies the hosts.

If another IP has the same first three octets, it is on the same network.

The doors

If the sender sends a direct message to a terminal, he must have processed the complete IP address, also using the mask that allows him to arrive at the door of his house or room, but at that point, he will have to knock to enter: an IP address or an Internet protocol is used to provide data through network connections.

This address is made up of a string of numbers that act as a unique identifier.

Port numbers are an unsigned, 16-bit integer added to this string, separated by a colon, such as 10.100.100.100:5000.

This added number is called a "port number" and is used to direct Internet traffic as it arrives at a server or independently assigned to a client by the operating system.

Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) are used to route a data packet to the correct process.

There are numerous port numbers and they are a fundamental part of the functioning of Internet networks.

Internet port numbers are numeric identifiers (0 to 65535) that direct data packets to specific applications on a computer, dividing traffic between services such as Web (HTTP 80, HTTPS 443), Email (SMTP 25, POP3 110, IMAP 143), File (FTP 21), and Name Resolution (DNS 53), with ports 0-1023 reserved for standard services (Well-Known Ports) and the others for dynamic or registered uses.

 

In particular, the common ports associated with services are:

Well Known Ports (0-1023): Standardized services.

21 (TCP): FTP (File Transfer Protocol) for file transfer.

23 (TCP): Telnet for remote access (less secure).

25 (TCP): SMTP (Simple Mail Transfer Protocol) for sending emails.

53 (TCP/UDP): DNS (Domain Name System) to translate names into IPs.

80 (TCP): HTTP (HyperText Transfer Protocol) for web browsing.

110 (TCP): POP3 (Post Office Protocol) for email reception.

143 (TCP): IMAP (Internet Message Access Protocol) for email management.

◦ 443 (TCP): HTTPS (HTTP Secure) for secure (encrypted) web browsing.

Registered Ports (1024-49151): for specific applications (e.g. RDP 3389, NTP 123).

Dynamic/Private Ports (49152-65535): used for temporary connections.

Ports are critical because a single IP address can handle many services at once; the port number tells the operating system which application (e.g. web browser, email client, DNS server) should receive incoming data, separating communications.

 

intranet:

Intranets are private, secure computer networks used exclusively by members of an organization (such as employees and collaborators) to share information, documents and resources, improve internal communication and organize activities. They use the same technologies as the Internet, such as TCP/IP, but are protected from unauthorized access via firewalls and passwords.

Main features:

Information sharing: Allow the sharing of documents, business procedures and other files in a centralized way.

Communication: Include tools such as forums, message boards and instant messaging to foster collaboration between employees.

Centralized access: Function as a single point of access for company resources, optimizing time and simplifying tasks.

Management and security: Offer a controlled environment to manage internal resources and protect confidential data from external access.

Training: Can be used to distribute educational materials, online courses and company updates.

 Difference with the Internet:

The Internet: it is a public and global network, accessible to anyone.

Intranet: is a private, local network, accessible only to a select group of people within an organization.

 


The Extranet represents a controlled extension of the Intranet, accessible to selected external users, such as suppliers, customers or business partners and functions as a bridge between the internal network and the outside world, allowing limited sharing of information and resources.

Network devices

Network devices are equipment that handle data traffic, such as routers, modems and switches, manage traffic, send and receive messages within the network.

modems:

It is the device that connects to the provider's line (e.g. telephone or fiber) to establish a connection with the Internet.

Routers:

It is that device that is responsible for distributing this connection to multiple devices within the local network.

Wireless routers have antennas to transmit the Wi-Fi signal, connecting wireless devices.

Modem routers:

A single device that combines both functions, acting as both a modem and a router.

access points:

This is a networking device that connects wireless equipment, such as smartphones and laptops, to a wired local area network (LAN) via Wi-Fi.

It's different from a router, although the features are often built into modern Wi-Fi routers; an AP acts as a wireless bridge, extending Wi-Fi range into an area where the signal is weak or non-existent.

The access point connects via an Ethernet cable to an existing router, creating a separate wireless network or extending an existing one.

Once connected, the AP creates a Wi-Fi access point for devices to connect to.

Wireless devices communicate with the access point, which in turn forwards network traffic to the main router and then to the Internet.

The differences between a router and an AP could be summarized as follows: a router manages the entire network, assigns IP addresses and provides Internet access, while an AP is specifically responsible for creating and managing the wireless connection.

Many modern home devices combine the functions of a router, modem and access point into a single device called a modem router.

Extension capabilities: An access point is ideal for extending Wi-Fi coverage, especially in large homes or offices where the main router's signal doesn't reach everywhere.

Physical connection: unlike a range extender or Wi-Fi repeater that receives the signal via cable (wireless), an access point connects via Ethernet cable to the router, ensuring a more stable and faster connection.

Access: An access point does not manage the assignment of IP addresses or the firewall, tasks that remain the responsibility of the router.

Hubs:

A hub is a simple device that repeats data to all ports.

Switches:

A switch is a network device that connects multiple devices (such as computers, printers, servers) in a local area network (LAN), allowing them to communicate with each other efficiently by forwarding data packets directly to the recipient, instead of sending them to everyone, unlike hubs.

Gateways:

A gateway (or "gate") in computing is a hardware/software device that connects two different networks, translating protocols to allow communication, like your router connecting your local network to the Internet (default gateway). There are many types, from payment gateways for online transactions to IoT gateways for sensors, to VPN gateways for remote access, acting as an entry/exit point and translating different formats to ensure interoperability and security between different systems.

IoT devices:

IoT (Internet of Things) devices are physical objects equipped with sensors, software and network connectivity that allow them to collect, exchange and transmit data via the Internet.

Common examples include smartphones, smartwatches, voice assistants such as Alexa and Google Home, smart appliances (e.g. refrigerators), home security systems, and industrial components, these devices allow you to automate processes, improve efficiency and provide convenience in everyday life and in professional settings.

Clients:

It is a device (or software) that requests services and data from a server, such as computers, smartphones, tablets, smart TVs, or even web browsers and email apps, which are programs that connect to servers to obtain information, making the client the party that "requests" and uses the resources of a network.

Servers:

It is a device, often a powerful computer or computer system, designed to provide services, resources and data (such as files, applications, email) to other devices or programs, called "clients", over a network (such as the Internet).

It can be a hardware entity (the physical computer) or software (the program that handles requests), but commonly the term refers to a dedicated physical machine, capable of running 24/7 to handle requests from many users at the same time, such as a website or email service.

Terminals:

Devices with which users interact, and can be classified based on various characteristics:

Computer (Desktop/Laptop): complete devices for every need.

Mobile Devices: smartphones and tablets that use cellular or Wi-Fi connections.

IoT devices: thermostats, cameras, voice assistants, connected cars, etc.

Printers/Scanners: network devices for printing and scanning etc.


these devices can be connected to the network using different technologies:

Wired Network: ADSL, Optical Fiber (FTTH, FTTC).

Wireless:

FWA (Fixed Wireless Access): Fixed connection via radio waves (antennas).

Satellite: For remote areas, via satellite dish.

Mobile (4G/5G): Via SIM, router, AP (soap bar etc.).


The estimate of global internet terminals is huge and growing, including billions of connected users (over 5.5 billion in 2025), but more importantly devices exceeding 14 billion, with projections of over 30 billion by 2025 for IoT, plus smartphones, PCs and other network objects.


 

network protocols

Network protocols are sets of “grammar rules” that define how devices communicate and exchange data over a network.

They function as a "common language" that allows different systems to talk to each other efficiently and accurately, specifying how to package, send, and receive data.

These "protocols" guarantee that physical systems, network hardware devices and "terminals", or end users, are able to communicate with each other, despite their structural differences. IP (Internet Protocol), for example, has the purpose of identifying and addressing data packets.

 

Examples of common protocols

  • IP (Internet Protocol): routing system for data packets to the correct destination through addressing.

  • TCP (Transmission Control Protocol): It is responsible for establishing a reliable connection and ensuring that all packets arrive at their destination correctly, in a precise order.

  • UDP (User Datagram Protocol): A faster and less "expensive" protocol than TCP, which does not guarantee delivery in the correct order, used for applications that do not require high reliability (such as video streaming).

  • HTTP(s) (HyperText Transfer Protocol): Protocol used for transferring web pages.

  • ICMP (Internet Control Message Protocol): Used to send error and control messages, as in the ping command to check the reachability of a host.

  • SMTP, POP3, IMAP: specific protocols for sending and receiving emails.



Data and application formats

  • JSON (JavaScript Object Notation): a lightweight and readable format, widely used for exchanging data between web and mobile applications (API).

  • XML (Extensible Markup Language): a structured format for defining and transmitting complex data, used in various industries.

  • HTML (HyperText Markup Language): it is not a programming language, but the markup language for structuring the content of web pages, which is then interpreted by browsers.

In summary, while TCP/IP is the technical foundation, HTTP/HTTPS and formats like JSON/XML are the specific "languages" that users and applications use every day to interact and exchange content on the web.

To those described above, for systems that require extreme speed and bandwidth saving (such as microservices or data streaming), formats that are not directly readable by humans must be added:


  • Protocol Buffers (Protobuf): Developed by Google, it is a compact binary format ideal for high-performance communications between servers.

  • Avro and Thrift: Mainly used in Big Data ecosystems and distributed systems due to their efficiency in managing evolutionary data patterns.

In any case, in these modern times, where automation reigns supreme, reference is made to the method for exchanging documents and data called EDI, acronym for (Electronic Data Interchange), which using secure protocols such as AS2/AS4, IT systems (management, ERP) speak to each other directly by exchanging structured data, without human intervention.

All this long introduction, to lead the reader to conceive a practical example.

 


 

Clients and servers

In summary, it is a system of devices using a structured dialogue: the client asks, the server responds, and the protocols ensure that both speak the same "language" across the network path they share.

The client sends a request to the server, for example using a GET or POST call method, directing it to the correct IP and port, using a protocol (e.g. HTTP(s)).

GET method

  • Purpose: Request (retrieve) data from a specified resource.

  • Data Sending: parameters added directly to the URL (e.g. ?param1=value&param2=value).

  • Visibility: the data is visible in the browser address bar.

  • Limitations: Limited amount of data (approximately 1500 characters).

  • Use: searches, filters, navigation, bookmarks.

  • Security: less secure for sensitive data (e.g. passwords) because the data is clear in the URL

POST method

  • Purpose: Send data to a server to create or update a resource.

  • Data Sending: Data sent in the body of the HTTP request, not in the URL.

  • Visibility: hidden data in the request body.

  • Limitations: No practical limit on data size.

  • Use: login form, registration, sending comments, uploading files.

  • Security: Safer for sensitive data when used with HTTPS, as the data is not exposed in the URL.

 

A practical case

Suppose you want to monitor two parameters relating to physical environmental quantities, for example temperature and humidity and you want to send them to a server for possible processing or display on a web page: you need two devices, a client, which can be made up of a Raspberry Pi Pico w, which acquires data from a specific sensor, for example the DHT11, and a server, for example a Raspberry Pi 4B, equipped with a touch screen for displaying the data acquired by the client, on a page web, possibly also reporting the data processed for setting alarms.

The server could in turn transfer the data to another client device, to control the drives, based on the processing of the processed values.

 

The Client.

In this case we thought of a device suitable for making a WIFI connection, which could also be equipped with a humidity and temperature sensor, such as the Raspberry Pi Pico w:

 

 


which is a microcontroller, designed specifically for electronics, IoT and physical computing projects, unlike traditional Raspberry Pis (like the 4 or 5) which are single board computers with an operating system, the "W" version adds Wi-Fi connectivity, making it ideal for applications requiring wireless communication, programmable in C/C++ and MicroPython, this microcontroller is based on Raspberry PI's RP2040 chip.

 

The temperature and humidity sensor.

The DHT11 is a relative humidity and temperature sensor that outputs a digital signal.

It uses a capacitive humidity sensor and a thermistor to measure the humidity and temperature of the surrounding air.

 


The temperature measurement range of the DHT11 is from 0°C to +50°C, with an accuracy of ±2°C.

The humidity measurement range is from 20% to 90%, with an accuracy of ±5%.

The sensor's sampling rate is 1Hz, which means that sensor data can only be read once per second.

Operating principle of the component:

The humidity sensing component is used to measure humidity, and has two electrodes with moisture-holding substrate (usually salt or conductive plastic polymer) sandwiched between the electrodes.

Ions are released from the substrate while water vapor is absorbed by the substrate, which in turn increases the conductivity between the electrodes.

The change in resistance between the two electrodes is proportional to the relative humidity. Higher relative humidity decreases the resistance between the electrodes, while lower relative humidity increases the resistance between the electrodes.

The temperature sensing part of the DHT11 sensor consists of an NTC thermistor.

A thermistor is a thermal resistor, a resistor that changes its resistance with temperature.

Technically, all resistors are thermistors, their resistance changes slightly with temperature, but the change is usually small and difficult to measure. Thermistors are made so that the resistance changes dramatically with temperature.

The variation can be 100Ω or more per degree of temperature.

The term NTC means Negative Temperature Coefficient, which means that the resistance decreases as the temperature increases.

At the output, there is a small PCB with an 8-bit configured integrated circuit (SOIC14).


 

The integrated circuit measures and processes the analog signal with stored calibration coefficients, performs analog-to-digital conversion, and outputs a digital data signal containing information for temperature and humidity.






PINOUT:

The Power Pin (+): Provides power to the sensor.

Although the supply voltage can vary between 3.3V and 5V, a 5V supply is recommended.

In case of 5V power supply, a cable connecting the sensor to the microcontroller can be up to 20 meters long.

However, with a supply voltage of 3.3V, the cable length should not be more than one meter, otherwise the line voltage drop will lead to measurement errors.

The OUT Pin (DATA): is the data pin, and is used for communication between the sensor and the microcontroller.

The GND Pin (-): is the "ground" pin and must be connected "to the common ground", or 0V.

For the Raspberry Pi Pico w, the pinout is shown in the following image:


The connection between the Raspberry Pi Pico – W and the DHT11 can be made, for example, using Pico-W Pin No. 26 (3.3V Out), Pin 38 (GND), or another with the same function, and Pin No. 1 (GP0).



The software for the Client

MicroPython is a streamlined and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimized for execution on microcontrollers and in constrained environments.

The MicroPython pyboard is a compact electronic circuit that runs MicroPython on bare metal, offering a low-level Python operating system that can be used to control all types of electronic projects.

MicroPython is packed with advanced features like an interactive prompt, arbitrary precision integers, closures, list comprehension, generators, exception handling, and more.

Yet it is compact enough to install and run in just 256k of code space and 16k of RAM.

MicroPython aims to be as compatible as possible with regular Python to allow code to be easily transferred from the desktop to a microcontroller or embedded system.

MicroPython, in summary, is a complete Python runtime compiler that works at a low level, managing to get an interactive prompt (REPL) to immediately execute commands, along with the ability to run and import scripts from the built-in filesystem.

REPL has history, tab completion, auto-indentation, and paste mode for a great user experience, very similar to Python.

In addition to implementing a selection of core Python libraries, MicroPython includes modules such as "machine", designed specifically for accessing low-level hardware.


Micropython code listing

# versione B_01 
# ok lettura sensore DHT11
# ok connessione
# ok trasmissione dati al server
import network
import urequests
import time
from machine import Pin
import dht

# --- CONFIGURATION ---
SSID = 'xxxxxx'
PASSWORD = 'yyyyyy'
SERVER_URL = 'http://10.100.100.100:5000/upload' # Replace with RPi server IP address
DHT_PIN = 0 # GPIO pin connected to DHT11

# --- SETUP ---
wlan = network.WLAN(network.STA_IF)
sensor = dht.DHT11(Pin(DHT_PIN))

def connect_wifi():
    """Connect to the WiFi network."""
    wlan.active(True)
    wlan.connect(SSID, PASSWORD)
    
    print('Connecting to WiFi...')
    max_wait = 10
    while max_wait > 0:
        if wlan.status() < 0 or wlan.status() >= 3:
            break
        max_wait -= 1
        print('waiting for connection...')
        time.sleep(1)
        
    if wlan.status() != 3:
        raise RuntimeError('Network connection failed')
    else:
        print('Connected')
        status = wlan.ifconfig()
        print('IP = ' + status[0])


def send_data(temp, hum):
    """Send temperature and humidity to the server."""
    data = {'temperature': temp, 'humidity': hum}
    try:
        response = urequests.post(SERVER_URL, json=data)
        print('Data sent:', response.text)
        response.close()
    except Exception as e:
        print('Failed to send data:', e)

# --- MAIN LOOP ---
try:
    connect_wifi()    
    while True:
        try:
            print('Reading sensor...')
            sensor.measure()
            temp = sensor.temperature()
            hum = sensor.humidity()     
            print(f'Temperature: {temp} C, Humidity: {hum}%')       
            send_data(temp, hum)       
        except OSError as e:
            print('Failed to read sensor.')
            
        # Wait for 300 seconds (5 minutes)
        print('Waiting 300 seconds...')
        time.sleep(300)
        
except Exception as e:
    print('An error occurred:', e)

 

 

The Server

The server could be made up of any PC or network device, but for this educational project, I chose an SBC (single-board computer) from the same family as the Client, also because it is economically affordable for all those who want to experiment with electronic applications, or for educational laboratories of all levels.

The history of the Raspberry Pi begins in 2006 with the idea of Eben Upton and the Raspberry Pi Foundation (UK) to create a low-cost microcomputer to teach programming to students, inspired by the Amiga and BBC Micro computers.

Launched in 2012, it is for all intents and purposes, a single board computer (SBC) made famous for its affordable price, compact design and versatility, transforming from an educational tool into a global phenomenon for hobbyists, makers and even for industrial applications.


From origins to success (2006-2012)

  • Birth of the idea (2006): Eben Upton and a group of academics and enthusiasts begin to conceive of a small, inexpensive computer to stimulate interest in computing and programming.

  • Prototypes: The first prototypes were based on Atmel microcontrollers, but the goal was to create a more powerful and versatile device.

  • Creation of the Foundation: The Raspberry Pi Foundation, a non-profit organization based in Cambridge, was created to promote the project.

  • Launch (2012): The first model, the Raspberry Pi 1 Model B, is released in February 2012, with a single-core processor, 256/512 MB of RAM and HDMI/USB outputs.

 

Evolution and expansion (2012-Present):

  • Unexpected success: The device becomes much more popular than expected, being adopted even outside the educational context for robotics, home automation and hobby projects.

  • Models and upgrades: Numerous models are released, with more powerful CPUs (quad-core), more RAM (up to 8GB) and advanced features, always maintaining a competitive price.

  • Software: Dedicated operating systems such as Raspberry Pi OS (formerly Raspbian) are created, optimized for the platform.

  • Applications: From education it expands to IoT, industrial monitoring and rapid prototyping, becoming an indispensable tool for developers and makers.

     

The role of Raspberry Pi:

  • Democratization of computing: Has lowered barriers to entry, making learning programming and electronics accessible to all.

  • Flexibility: With standard ports (USB, HDMI, Ethernet, GPIO), it allows you to easily connect peripherals and sensors, fueling creativity.

  • Strong community: A large community of users continuously supports and develops new projects and solutions.

 

PINOUT Raspebrry PI 4B


 

The operating system

Raspberry Pi OS is a free Debian-based operating system optimized for Raspberry Pi hardware.

The Raspberry Pi operating system supports over 35,000 Debian packages.

Since the Raspberry Pi operating system derives from Debian, it follows a staggered version of the Debian release cycle and therefore, new distributions occur approximately every 2 years.

Debian is Free Software: Debian is made with Free and open source Software and will always remain 100% Free.

This means: Freedom for anyone to use, modify and distribute it.

Debian is also free.

The history of Debian:

The history of Debian begins in August 1993 with Ian Murdock, who created a free and open GNU/Linux distribution, based on the Linux kernel, with the aim of being carefully maintained by the free software community.

The name is due to the composition of the two names Debra and Ian Deb+Ian (debra is Ian's partner). After a modest start, it grew into a large community, published its Manifesto in '94, released the first stable version (1.1 "Buzz") in '96, and became notable for its package management system (APT) and its philosophy of transparent, collaborative development.

Birth and foundation:

  • 1993: Ian Murdock launches the project to create a Linux distribution that was completely open, in line with the GNU spirit.

  • Debian Manifesto: Published in January 1994, defines the fundamental principles of the project.

     

Development and growth:

  • First stable version (1.1 "Buzz"): Released in June 1996, it marked the beginning of a tradition of code names based on Toy Story characters.

  • Succession: Bruce Perens succeeded Ian Murdock as project leader and introduced the code-naming convention.

  • Social Contract: Approved in 1997, defines Debian's commitments to free software.

  • Innovation: Introduced the APT (Advanced Package Tool) package management system and the .deb package format, making software updates and management much easier and more stable.

  • Expansion: It became one of the most important Linux distributions, becoming the basis for many others (such as Ubuntu) and supporting numerous hardware architectures.


Distinctive features:

  • Transparency and Community: One of the few major non-commercial distributions with an open and well-documented development process.

  • Stability: Famous for its stability, achieved through careful management of package dependencies.

  • Philosophy: Dedication to free software, with a strong commitment to ethical principles and freedom!


In this regard, I recommend reading one of my books which is published on the Amazon platform:

 


Of which I report a short excerpt from the preface written by Cheshire cat AI. (https://cheshirecat.ai/):

..."In an increasingly connected and interconnected world, the Open Source philosophy stands as a guiding light for those seeking the sharing of knowledge and creativity. With its deep roots in the culture of free software, Open Source embraces the idea that progress should not be hindered by restrictions or secrecy, but rather encouraged by collaboration and transparency.
The Open Source philosophy celebrates the idea that software, knowledge and ideas are accessible to all. Through sharing and collaboration, creative minds can bring extraordinary projects to life, pushing the boundaries of innovation and opening up new possibilities. Open Source is a call to the community, an invitation to participate and contribute in a meaningful way.”…

Server software

Flask is a lightweight and flexible Python micro-framework used to build web applications and APIs, acting as a software server handling HTTP routes, database interactions and template rendering (Jinja2) to generate dynamic responses, with an integrated server for development and the ability to deploy to real servers (such as Gunicorn/uWSGI) for production, ideal for those who want control and simplicity, from simple interfaces to complex systems.

How it works as a server:

  • Micro-framework: Provides only the essential foundations, allowing you to add external libraries for specific functionality, making it flexible.

  • Routing: Map URLs (e.g. /login, /products) to specific Python functions that handle the logic for those requests.

  • HTTP Requests/Responses: Handles incoming requests (GET, POST, etc.) and returns responses (HTML, JSON, etc.).

  • Development Server: Includes a built-in WSGI (Werkzeug) server for testing the app locally with app.run().

  • Rendering Template: Use Jinja2 to create dynamic HTML pages by inserting Python data directly into HTML files.

  • Extensibility: Integrates with many extensions to add features such as authentication (Flask-Login), databases (SQLAlchemy), and more.

Main use cases:

  • Backend web development: Create RESTful APIs or complete websites.

  • Scripting tools: Web interfaces for scientific or data analysis scripts.

  • IoT: Small embedded web servers.

  • Rapid Prototyping: Quickly launch a server for a project.

From development to production:

  • Embedded server is used during development.

  • For deployment, you use more robust WSGI servers like Gunicorn or uWSGI, often behind a reverse proxy like Nginx, to handle real traffic.

The software inherent to a device that pretends to be a Server can be conceived in two distinct parts:

The “Backend” part (server side) manages the business logic, databases and infrastructure hidden from the user (managed by software such as Python, Node.js, Java), while the “Frontend” part (client side) is the visible and interactive user interface (managed by software and languages HTML, CSS, JavaScript, React, Vue) that communicates with the backend via API, both essential for the complete functioning of a web or mobile application.

The frontend deals with what you see and allows interaction, the backend with how things work behind the scenes.

Frontend (Client Side):

  • What it is: The part of the application that the user sees and interacts with directly (user interface).

  • What it does: Page rendering, interactivity, responsive design, user experience (UX).

  • Common Technologies: HTML, CSS, JavaScript, and frameworks/libraries such as React, Angular, Vue.js.

  • Example: A login form (if any), buttons, icons, website layout.

Backend (Server Side):

  • What it is: The “behind the scenes” part that makes everything work, not visible to the user.

  • What it does: Manages data (database), application logic, security, authentication, communication with other services.

  • Common Technologies: Languages ​​such as Python (Django, Flask), Node.js (Express), Java (Spring), PHP, Ruby; Databases like MySQL, PostgreSQL; Servers like Apache, Nginx.

  • Example: Save monitoring data, process data and set alarms, manage icons, buttons and send commands to other clients.

How They Collaborate:

  • The backend processes (always listening) processes the received data (possibly saves the data in a database) and sends a response to the frontend.

  • The frontend (always available to the user) exposes the processed data and awaits any commands (e.g. "modify alarm settings") from the backend.

  • APIs (Application Programming Interfaces) are the crucial bridge for this communication, allowing frontend and backend to "converse".


 

In this minimal application, for educational use, we have tried to reduce to the essentials the software complexity necessary for managing the application by following the basic lines inherent to the Flask architecture, organizing the software in the following folders:


The Index.html file

The index.html file is the main and input file of a website, an HTML page that is automatically loaded by the server when a user visits the domain, for the Flask framework, this page is located in a specific folder called templates.

It is written in HTML (HyperText Markup Language) to organize text, images, links and other elements.

The file is read by the browser (Chrome, Firefox, etc.) and displayed as an interactive web page.

Its operation can be integrated with scripts from other languages, which affect its appearance (such as CSS style sheets) and interactivity, such as JS (JavaScript) code to add dynamic functionality, interactive buttons and data manipulation.

 

The index.html listing

<html lang="it">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IoT Dashboard - Raspberry Pi</title>
    <!-- Refresh page every 30 seconds to fetch new data -->
    <meta http-equiv="refresh" content="30">
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <!-- Google Fonts for premium look -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

    <linkhref="https://fonts.googleapis.com/                                                css2? family=Outfit:wght@300;400;600&display=swap" rel="stylesheet">
</head>
<body>
    <div class="container">
        <header>
            <h1>Monitoraggio Ambientale</h1>
            <p>Ultimo aggiornamento: {{ data.last_updated if data.last_updated else 'In attesa di dati...' }}</p>
        </header>
        <main class="dashboard">
            <!-- Temperature Card -->
            <div class="card {% if alarms.temp_alarm %}alarm-{{ alarms.temp_alarm }}{% endif %}">
                <div class="icon">??</div>
                <h2>Temperatura</h2>
                <div class="value">
                    {% if data.temperature is not none %}
                        {{ data.temperature }} C
                    {% else %}
                        --
                    {% endif %}
                </div>
                <div class="status">
                    {% if alarms.temp_alarm == 'min' %}
                        ?? ALLARME: Temperatura Bassa (< 5 C)
                    {% elif alarms.temp_alarm == 'max' %}
                        ?? ALLARME: Temperatura Alta (> 25 C)
                    {% else %}
                        Normale
                    {% endif %}
                </div>
            </div>
            <!-- Humidity Card -->
            <div class="card {% if alarms.hum_alarm %}alarm-{{ alarms.hum_alarm }}{% endif %}">
                <div class="icon">?</div>
                <h2>Umidity</h2>
                <div class="value">
                    {% if data.humidity is not none %}
                        {{ data.humidity }} %
                    {% else %}
                        --
                    {% endif %}
                </div>
                <div class="status">
                    {% if alarms.hum_alarm == 'min' %}
                        ?? ALLARME: Umidity Bassa (< 20%)
                    {% elif alarms.hum_alarm == 'max' %}
                        ?? ALLARME: Umidity Alta (> 75%)
                    {% else %}
                        Normale
                    {% endif %}
                </div>
            </div>
        </main>
        <footer>
            <p>Server: Raspberry Pi | Client: Pico W</p>
        </footer>
    </div>
</body>
</html>

 

Notes:

Note that two "cards" are called, provided by App.py to expose the data on the index.html page, whose style is architected via a style file: syles.css.



 

The syles.css file

Cascading Style Sheets (CSS) are a collection of formatting rules that control the appearance of the content on a web page.

This architectural typology is used to format a page, the content is therefore separated from the presentation.

The HTML code is therefore found in the HTML file, while the CSS rules that define the presentation of the code are found in another file (an external style sheet and, in the case of use of flask, in the static folder) but in other cases it can coexist in the HTML listing (generally in the head section).

By separating the content from the presentation, it is much easier to manage the appearance of the site from a single point of control, since it is not necessary to update every property of each page when you want to make a change, moreover, you get a simpler and “cleaner” HTML code, which shortens loading times in the browser and simplifies navigation.

CSS offers more flexibility and more control over the details of how your pages look.

With CSS you can control many text properties:

  • particular fonts and font sizes;

  • formatting elements such as bold, italics, underlining and text shading;

  • text color and background color;

  • color and underlining of links; etc.

By using CSS to control fonts, you can also manage the layout and appearance of the page more consistently regardless of the browser you use.

In addition to text formatting, you can use CSS to control the format and position of block-level elements on a web page.

A block-level element is a self-contained piece of content, usually separated by a newline character in HTML code and visually formatted as a block. In this case the "cards" provided by the Flask App.

You can set margins and borders for elements at the block level, place them in a specific position, add a background color to them, make text flow around them, and so on.

Block-level element manipulation is essentially how you organize the layout of your pages when using CSS.

 

The styles.css listing

:root {
    --bg-color: #0f172a; /* Dark blue/slate background */
    --card-bg: #1e293b;
    --text-primary: #f8fafc;
    --text-secondary: #94a3b8;
    --accent-color: #38bdf8; /* Cyan */
    --alarm-min: #0ea5e9; /* Blue for cold/low */
    --alarm-max: #ef4444; /* Red for hot/high */
    --alarm-bg-min: rgba(14, 165, 233, 0.2);
    --alarm-bg-max: rgba(239, 68, 68, 0.2);
    --success-color: #22c55e;
}
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
body {
    font-family: 'Outfit', sans-serif;
    background-color: var(--bg-color);
    color: var(--text-primary);
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}
.container {
    width: 100%;
    max-width: 800px;
    padding: 2rem;
    text-align: center;
}
header h1 {
    font-weight: 600;
    font-size: 2.5rem;
    margin-bottom: 0.5rem;
    background: linear-gradient(to right, var(--accent-color), #818cf8);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}
header p {
    color: var(--text-secondary);
    margin-bottom: 3rem;
    font-size: 1.1rem;
}
.dashboard {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 2rem;
}
.card {
    background-color: var(--card-bg);
    border-radius: 1.5rem;
    padding: 2rem;
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    border: 1px solid rgba(255, 255, 255, 0.1);
}
.card:hover {
    transform: translateY(-5px);
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.2);
}
.icon {
    font-size: 3rem;
    margin-bottom: 1rem;
}

.card h2 {
    font-weight: 400;
    color: var(--text-secondary);
    font-size: 1.2rem;
    text-transform: uppercase;
    letter-spacing: 0.1em;
    margin-bottom: 1rem;
}
.value {
    font-size: 4rem;
    font-weight: 600;
    margin-bottom: 1rem;
}
.status {
    padding: 0.5rem 1rem;
    border-radius: 9999px;
    background-color: rgba(255, 255, 255, 0.05);
    display: inline-block;
    font-size: 0.9rem;
}
/* Alarm States */
.card.alarm-min {
    border-color: var(--alarm-min);
    background-color: var(--alarm-bg-min);
}
.card.alarm-min .value {
    color: var(--alarm-min);
}
.card.alarm-max {
    border-color: var(--alarm-max);
    background-color: var(--alarm-bg-max);
}
.card.alarm-max .value {
    color: var(--alarm-max);
}
footer {
    margin-top: 4rem;
    color: var(--text-secondary);
    font-size: 0.8rem;
}
@media (max-width: 600px) {
    header h1 {
        font-size: 2rem;
    }
    .value {
        font-size: 3rem;
    }
}

 

CSS In summary:

  • Formatting language: CSS defines how HTML/XML documents are presented.

  • Separation: Separate content (HTML) from presentation (CSS), making sites more manageable and accessible.

  • "Cascading": Rules are applied in a specific order, allowing more specific styles to override more general ones.


How they work (basic syntax)

  • A CSS sheet is made up of rules.

  • Each rule has a selector (e.g. p, #myId, .myClass) and a block of declarations {},.

  • Declarations are property: value pairs; (e.g. color: blue;


The Flask App

The fundamental points for using a flask application can be identified as follows:

  1. Installation: It is installed via pip (pip install flask).

  2. Creating the instance: You create a Flask(__name__) object.

  3. Routing: You define the routes (URLs) that map Python functions (e.g. @app.route('/')).

  4. Request management: Objects such as requests are used to manage form data (POST).

  5. Rendering: Use render_template() to generate HTML pages dynamically from templates (.html files in the templates folder).

  6. Sessions and Security: You manage user sessions via cookies and configure a secret key (SECRET_KEY) for security, preferably with extensions like Flask-Login for real applications.

The language used is Python!

The history of Python begins in 1989, when the Dutch programmer Guido van Rossum began working on it during the Christmas holidays, releasing the first version in 1991; the name comes from the British comedy group Monty Python, not from snakes, reflecting the intent to create a simple, readable and entertaining language.

Python has evolved from a personal project to a high-level programming language, widely used due to its clear syntax, flexibility and extensive library, becoming one of the most popular for web development, data analysis and AI.

Birth and first versions:

  • 1989: Guido van Rossum begins development of Python, inspired by the ABC language and looking for a vacation scripting language.

  • 1994: Python 1.0 is released, introducing features such as map, filter, and reduce

Development and diffusion:


  • 2000: Python 2.0 is released, with Unicode support and list improvements.

  • 2008: Python 3.0 is released, introducing significant changes such as the print() function and improvements in numeric handling.

  • Philosophy: Guido van Rossum, as "Benevolent Dictator For Life" (BDFL), led the development, emphasizing readability of the code (similar to English) and ease of use.

  • Popularity: Its simplicity makes it ideal for beginners, while the power and libraries make it suitable for professionals for web development (Django, Flask), data science, machine learning and scripting.

    Python is an open source, free, freely usable, modifiable and distributable programming language for commercial purposes, supported by a license approved by the Python Software Foundation (PSF), which makes it flexible, versatile and free of license costs for companies and developers.

 

The app.py listing

 # versione B_01 correzione errori utf8
# funziona su raspberyy pi 4b
from flask import Flask, render_template, request, jsonify
from datetime import datetime

app = Flask(__name__)

# Global variables to store the latest sensor data
# Initialize with None to indicate no data received yet
latest_data = {
    'temperature': None,
    'humidity': None,
    'last_updated': None
}

# Alarm thresholds
TEMP_MIN = 5.0
TEMP_MAX = 25.0
HUM_MIN = 20.0
HUM_MAX = 75.0

@app.route('/')
def index():
    """Render the dashboard with current data and alarm status."""
    data = latest_data.copy()
    alarms = {
        'temp_alarm': None,
        'hum_alarm': None
    }
    
    if data['temperature'] is not None:
        if data['temperature'] < TEMP_MIN:
            alarms['temp_alarm'] = 'min' # Low temperature alarm
        elif data['temperature'] > TEMP_MAX:
            alarms['temp_alarm'] = 'max' # High temperature alarm     
    if data['humidity'] is not None:
        if data['humidity'] < HUM_MIN:
            alarms['hum_alarm'] = 'min' # Low humidity alarm
        elif data['humidity'] > HUM_MAX:
            alarms['hum_alarm'] = 'max' # High humidity alarm
    return render_template('index.html', data=data, alarms=alarms)
@app.route('/upload', methods=['POST'])
def upload_data():
    """Receive sensor data from the client."""
    try:
        content = request.json
        temp = content.get('temperature')
        hum = content.get('humidity')    
        if temp is not None and hum is not None:
            latest_data['temperature'] = float(temp)
            latest_data['humidity'] = float(hum)
            latest_data['last_updated'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(f"Received data: Temp={temp} C, Humidity={hum}%")
            return jsonify({"status": "success", "message": "Data received"}), 200
        else:
            return jsonify({"status": "error", "message": "Invalid data format"}), 400
            
    except Exception as e:
        print(f"Error processing upload: {e}")
        return jsonify({"status": "error", "message": str(e)}), 500

if __name__ == '__main__':
    # Run server on all interfaces, port 5000
    app.run(host='0.0.0.0', port=5000, debug=True)


And finally here it is! The host who crosses the door of the room, to serve the extracts from the squeezing of the sensors on a silver platter, on crystalline glasses of HTML.



Reading tips:


 

 

Thanks for your attention.

Romeo Ceccato




 

No comments:

Post a Comment

Internet Bar (Clients and Servers)

    introduction The title is certainly ironic, but I wrote it because in this article, I would like to describe without going ...