<?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 Natan  on Medium]]></title>
        <description><![CDATA[Stories by Natan  on Medium]]></description>
        <link>https://medium.com/@yonatanjori?source=rss-543c6cda3bc3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RJBLG28sDfaeymOynKpsEQ@2x.jpeg</url>
            <title>Stories by Natan  on Medium</title>
            <link>https://medium.com/@yonatanjori?source=rss-543c6cda3bc3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 21:21:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yonatanjori/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[Jigsaw Dynamic Malware Analysis]]></title>
            <link>https://medium.com/@yonatanjori/jigsaw-dynamic-malware-analysis-11daa577a214?source=rss-543c6cda3bc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/11daa577a214</guid>
            <dc:creator><![CDATA[Natan ]]></dc:creator>
            <pubDate>Sun, 21 Nov 2021 19:14:26 GMT</pubDate>
            <atom:updated>2021-11-21T19:16:36.315Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Dotpeek</h4><p>Aaaand, we’re back to, yet again, another digital forensics thingies 🖥💻. This week’s episode is probably going to be fun as I explored one of the most famous ‘thingies’ in the digital forensics universe: yep you guessed it, malware.</p><p>There are lots of malware types that you can find, experience, and analyze. But now I am going to specifically discuss Jigsaw malware. Moreover, we are going to analyze the Jigsaw malware with dynamic analysis. Let’s take a closer look into it, shall we?</p><p>Dynamic analysis is a technique used to launch malware and analyze its behavior at run time. More specifically, Dynamic analysis refers to the process of analyzing a code or script by performing and observing the actions of the code or script. These actions can be observed at various levels, from the lowest possible level (the binary code itself) to the entire system (such as changes to the registry or file system). The purpose of dynamic analysis is to expose the malicious activity of an executable file while it is running, without compromising the security of the analytics platform.</p><p>We do not want to run the malware directly to avoid damage, so we take specific steps to isolate and analyze the malware execution. Dynamic analysis can be used to analyze the run-time behavior of malware. Unlike static analysis, we don’t need to understand exactly how packing works as an example. If the malware author used a custom packer, they would need to understand and start the analysis after unzipping to do a static analysis. For dynamic analysis, this may not be necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/0*Ar_9nObIMCkOGUOV.png" /><figcaption>Jigsaw Ransomware</figcaption></figure><p>Now, what about Jigsaw malware? Jigsaw ransomware created global mayhem in a series of attack cycles. This horror might rise from the dead once more, so you need to be protected. The Jigsaw ransomware encrypts the file and demands a ransom to retrieve the file, but Jigsaw comes with a countdown timer. As soon as the malware is deployed, the jigsaw clock will start ticking. Some files are deleted every hour for the first 24 hours. On the second day, the ransomware deletes hundreds of files, and on the third day, it deletes thousands of files until the ransom is paid. In addition, if you try to operate the ransomware or restart your computer, 1000 files will be deleted as of a “penalty”.</p><h4>The Dynamic Analysis on Jigsaw Ransomware</h4><p>For the ransomware file itself, we will be using the one provided <a href="https://github.com/LeechxSys/Jigsawsource">here</a>. Moreover, we can use Windows 7 on VM to do the analysis. First of all, obviously, we open the ransomware file and it will show something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*ha9hjt5FX4XHgXHvZ9-Mrg.png" /><figcaption>Confirmation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*VyvD_uL_frcDUY-79zr9lw.png" /><figcaption>Jigsaw Ransomware Initial Interface</figcaption></figure><p>With that, the Jigsaw ransomware is successfully executed and has injected some malicious processes. Now our objective is to look for the KillSwitch to then stop running the Jigsaw ransomware. The program jigsaw.exe was renamed to drpbx.exe after installation, and after restarting the computer to avoid this ransomware the ransomware will automatically be renamed to firefox.exe.</p><p>We will then be able to see lots of .fun files, which is one of the extensions for this Jigsaw ransomware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*T_QgT_BhZgvshY0PxqpGsA.png" /><figcaption>.fun Files</figcaption></figure><p>Now let’s try to analyze the ransomware. The Jigsaw ransomware was designed with the .NET framework. So, to decompile it, we can use the Dotpeek tool. With Dotpeek, we’re able to see the FormBackground.css, FormEncryptedFiles.css, Config.css that is used for the Jigsaw ransomware itself.</p><ul><li>FormBackground.css</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*XwQAvjlsLBghZEqD4x8OwA.png" /></figure><p>This part of the code is for the GUI of the Jigsaw interface itself and also for the timer that is running on the Jigsaw ransomware.</p><ul><li>FormEncryptedFiles.css</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*JenIcELaCX1ktkYdjiwdZQ.png" /></figure><p>With this part of the code and analyzing the DataGridView, and DataGridViewTextBoxColumn classes, we can know that the Jigsaw ransomware uses as192. This means that Jigsaw ransomware uses symmetric encryption for decoding the files: use a same key for encryption and decryption.</p><ul><li>Config.css</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*w6Aby7_sS0dKpA4gqWJ54g.png" /></figure><p>With this part of the code, we can know the ‘config’ of the Jigsaw ransomware. It clearly says on the EncryptionPassword constant, that the Encryption Password was ‘<strong>OoIsAwwF23cICQoLDA0ODe==’</strong>. Now again, this gives confusion, and we can <a href="http://rapidtables.com/convert/number/ascii-to-binary.html">translate this to a binary</a>, and it will convert to 01001111 01101111 01001001 01110011 01000001 01110111 01110111 01000110 00110010 00110011 01100011 01001001 01000011 01010001 01101111 01001100 01000100 01000001 00110000 01001111 01000100 01100101 00111101 00111101.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*ZtbPI6QGcN4Z0JLgd69mPA.png" /></figure><p>After removing the spaces on the binary, we know that the character count of the binary is 192. This indicates that the password is using 192-bit encryption.</p><p>The result of this Jigsaw malware execution is that all nonessential files are encrypted and they have a .fun extension. Moreover, we can find the AesCrytoServiceProvider function that tells us the encryption that is used is AES. Along with that, we can also know the CreateDecryptor function that is used for the decryption of the malware. These two classes are used for encrypting and decrypting the files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCKYrAXsZE6RlUy3JHjmhQ.png" /></figure><h4>In summation</h4><p>Jigsaw is a tricky malware, but as time develops, there are tons of tools that can be used for analyzing this malware, specifically for dynamic analysis. So do not panic and chill it, if you accidentally (or intentionally) plant this malware into your gadget. Do not pay this malware since there are tons of tools made for handling this malware, such as Dotpeek and <a href="https://www.bleepingcomputer.com/download/jigsaw-decrypter/">this</a>.</p><p>So, that’s it for today’s words of digital forensics-thingies, see you on another episode peeps!</p><blockquote><em>Writer:</em></blockquote><blockquote><em>Yonatan Jori Saputro</em></blockquote><blockquote><em>18218024</em></blockquote><blockquote><em>II4033 Digital Forensics</em></blockquote><blockquote><em>Tugas </em>Malware Dynamic Analysis</blockquote><p>Reference:</p><ul><li><a href="https://dl.acm.org/doi/fullHtml/10.1145/3329786">https://dl.acm.org/doi/fullHtml/10.1145/3329786</a></li><li><a href="https://medium.com/@jain.sm/malware-dynamic-analysis-338efc68a654">https://medium.com/@jain.sm/malware-dynamic-analysis-338efc68a654</a></li><li><a href="https://www.comparitech.com/net-admin/jigsaw-ransomware/">https://www.comparitech.com/net-admin/jigsaw-ransomware/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11daa577a214" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring and Forensics Tools on Linux]]></title>
            <link>https://medium.com/@yonatanjori/monitoring-and-forensics-tools-on-linux-aa698e9b7a54?source=rss-543c6cda3bc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa698e9b7a54</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[daemon]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[journalctl]]></category>
            <category><![CDATA[forensics]]></category>
            <dc:creator><![CDATA[Natan ]]></dc:creator>
            <pubDate>Sun, 31 Oct 2021 19:18:02 GMT</pubDate>
            <atom:updated>2021-10-31T19:18:02.174Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Daemon, journalctl, timedatectl</h4><p>On to the next episode of digital forensics thingies. After doing the monitoring and forensics on Windows, now we’re going to talk about monitoring and forensics on <em>other </em>operating system. (spoiler: it’s not macOS!)</p><p>I’m pretty sure you’ve heard of Linux. Linux is similar to other operating systems, such as Windows and macOS. Like other OS, Linux has a graphical user interface and the same type of software such as a word processor, image editor, and video editor. The Linux operating system comprises several different pieces: Bootloader, Kernel, Init System, Daemons, Graphical Server, Desktop Environment, and Applications (<a href="https://www.linux.com/what-is-linux/">Linux</a>).</p><p>It’s hard work to monitor and debug performance problems with Linux. If you have the right tools, then it will be easier to work. The term monitoring and forensics is pretty much across ‘operating system’. It contains several activites like logs analysis, operating system performance analysis, and even access and files analysis.</p><p>There are tons of how-to and tools on Linux monitoring and forensics. For now, I’m going to review the use of of <a href="https://www.kali.org/">Kali</a>. Let’s jump right into it.</p><h4>Daemon</h4><p>Daemons are service processes that run in the background to monitor your system and make features available to other processes. Daemons perform specific actions at predefined times or in response to specific events. There are many daemons running on Linux systems, each specially designed to monitor a small part of the system. Daemons are not really visible, but they are essential because it is not under the direct control of the user. Since a daemon does most of the work in the background, it can look a little ‘invisible’, so it can be difficult to identify and identify what you are actually doing. To start and stop daemons on your Linux operating system, you first need to access the<strong> /etc/init.d</strong> scripts directory on your OS.</p><p>In Linux, we can use several commands to identify or even configure daemons. First, we can identify or list the daemons that are running in our system. First, as I mentioned, we need to access the /etc/init.d first, so, do that first (cd /etc/init.d command). After that, we can simply type in ‘ls’ which is the command to view a list of the files and folders in a given directory. After that we will be able to see the list of daemons that exist in our operating system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*5emxdE6W48iQzDSkaypWJw.png" /><figcaption>ls command to list out the daemons</figcaption></figure><p>But that’s just for identifying the list of daemons. That’s neither useful nor beneficial for forensics. To add the information, we are able to identify whether a daemon is active or not. We’re able to do that through this command:</p><pre><strong>$ </strong>service –status-all</pre><p>With that command, we’ll be able to see the list of daemons and its status. The positive [+] and negative [-] signs before the daemon names, respectively, imply that they are either active or inactive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*rThZobUoVQzCeUwUlPAd9A.png" /><figcaption>daemons and its statuses</figcaption></figure><p>Next, I was able to know how to start, stop, and even restart daemons. The commands are pretty simple and stratight-forward. In Linux terminal, We can use these syntax rules to, respectively, start, stop, and restart a daemon:</p><pre><strong>$ </strong>service preferred-daemon-name start</pre><pre><strong>$ </strong>service preferred-daemon-name stop</pre><pre><strong>$ </strong>service preferred-daemon-name restart</pre><h4>journalctl</h4><p>journalctl is a command to view the logs collected by systemd. The systemd-journald service is responsible for collecting logs from systemd and pulling messages from the kernel, systemd service, and other sources. These logs are collected in a central location for easy viewing. Journal log records are structured and indexed so that journalctl can display log information in a variety of convenient formats.</p><p>Fist, we can use this command for the very basic use of journalctl. This command will then show our logs in a format similar to the traditional syslog format. Each line starts with the date, followed by the server’s hostname, the process name, and the message for the log.</p><pre><strong>$ </strong>journalctl</pre><pre>Oct 26 12:00:25 debian sshd[15844]: pam_unix(sshd:session): session opened for user example_user by (uid=0) <br>...</pre><p>Further, we can filter the list of logs using several commands like since and until. These are few examples:</p><pre><strong>$ </strong>journalctl — since “2021–08–30 14:10:10”<br><strong>$ </strong>journalctl — until “2021–09–02 12:05:50”<br><strong>$ </strong>journalctl — since “2021–08–30 14:10:10” — until “2021–09–02 12:05:50”</pre><p>With the help of journalctl, you can begin the process of troubleshooting why a service is doing or isn’t doing certain action. With this mechanism, you can compare system boots to see when a service was working properly versus when it wasn’t.</p><h4>timedatectl</h4><p>We can use timedatectl to query and change the system clock and its settings, and to enable or disable the time synchronization service. The timedatectl command is a useful utility that can be used with almost any Linux distribution that uses systemd. This command also has the utility to control the current time zone, date and time. It can also be used to enable automatic time synchronization with a remote NTP server. Also, when we use timedatectl to set the time, all real-time clocks (RTCs) connected to our system are reconfigured to use the correct time.</p><p>There are tons of <em>commands </em>that we can use in regards to this timedatectl command. Here are few examples.</p><p>The very first one it the most basic one, which is for identifying our time and date configuration in our operating system.</p><pre><strong>$ </strong>timedatectl</pre><p>We can use this command to get information about the current time setting. This command also provides local time, world time, RTC time (if available), and the currently defined time zone, as shown below. Further, it also shows the status of some functions of the timedatectl command, such as time synchronization status.</p><pre>               Local time: Min 2021–10–31 16:06:59 WIB<br>           Universal time: Min 2021–10–31 09:06:59 UTC<br>                 RTC time: n/a<br>                Time zone: Asia/Jakarta (WIB, +0700)                   System clock synchronized: yes<br>              NTP service: active<br>          RTC in local TZ: no</pre><p>Further than that, when the time zone is ready, we can set the time zone using the set-timezone function of the timedatectl command. With this, we must have superuser privileges to perform this action because we will change the system settings.</p><pre><strong>$ </strong>sudo timedatectl set-timezone “Australia/Hobart”</pre><p>And after that, if we use the timedatectl, we should see that the time and date configuration in our OS has been changed.</p><pre>               Local time: Min 2021–10–31 19:07:24 AEST<br>           Universal time: Min 2021–10–31 09:07:24 UTC<br>                 RTC time: n/a<br>                Time zone: Asia/Jakarta (WIB, +1000)                   System clock synchronized: yes<br>              NTP service: active<br>          RTC in local TZ: no</pre><p>With timedatectl, we also are able to set the time and date in our OS. Simply use set-time to do this. Here are few examples.</p><pre><strong>$ </strong>sudo timedatectl set-time “2020–09–07 15:50:00”</pre><pre><strong>$ </strong>sudo timedatectl set-time 2020–09–07</pre><pre><strong>$ </strong>sudo timedatectl set-time 15:50:00</pre><h3>Conclusion</h3><p>Linux monitoring and forensics are essential for us to examine our Linux computer, especially towards its programs, connections, performance, etc. There are lots of tools that we can use to do Linux monitoring and forensics. Some of the commands that we can use for that are <em>daemons, journalctl, </em>and <em>timedatectl. </em>With those tools/commands, we will be able to troubleshoot issues on the Linux system. In addition to that, with this commands, the ‘<em>forensic guy</em>’ will then be able to provide evidences if there are any attacks.</p><p>So, that’s it for today’s routine, see you on another episode peeps!</p><blockquote><em>Writer:</em></blockquote><blockquote><em>Yonatan Jori Saputro</em></blockquote><blockquote><em>18218024</em></blockquote><blockquote><em>II4033 Digital Forensics</em></blockquote><blockquote><em>Tugas Linux Forensics</em></blockquote><p>Reference:</p><ul><li><a href="https://itsfoss.com/linux-daemons/">https://itsfoss.com/linux-daemons/</a></li><li><a href="https://www.linode.com/docs/guides/how-to-use-journalctl/">https://www.linode.com/docs/guides/how-to-use-journalctl/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa698e9b7a54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring and Forensics Tools on Windows]]></title>
            <link>https://medium.com/@yonatanjori/monitoring-and-forensics-tools-on-windows-b3034ce522d4?source=rss-543c6cda3bc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3034ce522d4</guid>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[sysinternals]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[forensics]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[Natan ]]></dc:creator>
            <pubDate>Fri, 22 Oct 2021 01:43:32 GMT</pubDate>
            <atom:updated>2021-10-22T01:43:32.462Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Process Explorer, TCP View, PsLoggedOn, Access Enum</h4><p>Hi everyone! Back at it again with me on digital forensics story. In this episode, we’re going to learn a more specific forensic: Windows monitoring and forensics, especially its tools.</p><p>Microsoft Windows (Windows) is a several proprietary graphical operating system families, all of which are developed and marketed by Microsoft. To deep dive more into the topic, especially monitoring and forensics, there are some tools that we can use on Windows.</p><p>The tools are available through download <a href="https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite">here</a>. The tools that I used is from <strong>Sysinternals Suite</strong>. Sysinternals Suite is a suite of more than 70 freeware utilities that are used to monitor, manage and troubleshoot the Windows operating system, and which Microsoft now owns. These utilities are executable files that do not require installation to run.</p><p><strong>The Sysinternals</strong> site divides the utilities into six main categories: file and disk, networking, process, security, system information, and miscellaneous.</p><ul><li>File and disk: This section hosts utilities that monitor file usage and disk status.</li><li>Networking: This area features applications to troubleshoot and monitor connections on desktop and server systems.</li><li>Process: This section holds utilities to monitor and troubleshoot running applications.</li><li>Security: This area features security-based utilities, including Autoruns, which show the applications that start automatically when the system boots.</li><li>System information: This category hosts applications that display general information about a workstation or server.</li><li>Miscellaneous: Utilities in this section do not fit in other categories, and have limited diagnostic or troubleshooting capabilities.</li></ul><p>Now, let’s jump in to the tools!</p><h3>Monitoring</h3><p>Monitoring focuses on processes and threads that exist in Windows. An application will run single or multiple processes and one process contains at least one thread. In regards to that, all dedicated threads for a process will be contained within the same address to prevent corruption for another process. With that brief explanation, we know that monitoring is an important task to do in Windows so that we can examine how programs running on our computers affect our computer’s performance.</p><h4>Tools 1: Process Explorer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*pLyo_98KZJPVrN-T-afHcw.png" /><figcaption>Process Explorer</figcaption></figure><p>Process Explorer (procexp) can be used for lots of monitoring functions. Right of the bat, you can see on the attached image above, we know that procexp has these functions:</p><ul><li>Usage monitoring : CPU monitoring, physical memory monitoring, system commit monitoring</li><li>Kill a process or close a handle</li><li>Filter by name</li></ul><p>“But that’s basic. Task manager can also do that.” Hold on, peeps! Besides that, procexp also offers several unique functionalities.</p><ul><li>Save process data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/29/1*RUCv3YiTyngr9aiXCwaeOA.png" /><figcaption>Save Process Data</figcaption></figure><p>By clicking the save button, we will be able to save one process data into a txt file that will consist of this information: Process CPU, Private Bytes, Working, Set, PID, Description, and Company Name.</p><ul><li>Find Window’s process</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/30/1*krhGRSsflrmID1fAprYa7g.png" /><figcaption>Find Window’s Process</figcaption></figure><p>With the ordinary task manager, we can’t identify a certain program window or tab in relation to its process (or PID) in the task manager. With procexp, we can identify which window belongs to which part on the list of tasks/processes. What we have to do is just drag and drop the ‘find window’s process’ icon to the process that we would like to identify. From there, we will be able to do further action to the said process (i.e. killing the program, find thread information on the program, etc). This is very beneficial, especially if we have multiple process (or program) that runs under the same tab name. For example, if we open multiple command line tabs, and we would like to analyze the thread information on one of the cmd, we will be able to drag the icon and drop the icon to our desired cmd tab, from there, procexp will highlight which process is the chosen cmd on the process list, and from there we will be able to do the thread information for the chosen cmd.</p><ul><li>Thread information</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*SguCJ_0biu1C7a7fMbVUDA.png" /><figcaption>Thread Information</figcaption></figure><p>By double-clicking a process, we can identify the thread information of the process. From there we will be able to identity its thread ID (TID), CPU usage, cycles delta, suspend count, start address, state, kernel, base priority, dynamic priority, user, context switches, I/O priority, memory priority, ideal process, etc.</p><h4>Tools 2: TCP View</h4><p>TCP View is useful for us to identify the communication between the internet and our Windows operating system. With TCP View, we will be able to identify which program connections are lost/dumped, sent/synchronized, or on queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQHrVj2Jzp6Wsqog7HjIrA.png" /><figcaption>TCP View</figcaption></figure><p>TCP View will provide several informations regarding the connections or programs that are running. Those information includes process name, process id (PID), protocol, state, local address, local port, remote address, remote port, create time, module name, and status color coding.</p><p>The status color codings are as such:</p><ul><li>Green</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZzwSyR8147jO4qdbR50GQ.png" /><figcaption>Green Connections</figcaption></figure><p>Port will appear green as they pop up while being created (new endpoints).</p><ul><li>Yellow</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxFkQZiU3a4Gdp3-n8dFvw.png" /><figcaption>Yellow Connection</figcaption></figure><p>Port will appear yellow when creation is pending. Endpoints that change state from one update to the next are highlighted in yellow.</p><ul><li>Red</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYcQnVP159nx39QX50vbVQ.png" /><figcaption>Red Connection</figcaption></figure><p>ndpoints that have been closed will be highlighted in red. Ports that are deleted are shown in red.</p><h3>Forensic</h3><p>For Windows forensics, we need a clear methodology for data acquiring/retrieval and the analysis of those data. Specifically, Windows forensics are segmented into this:</p><ul><li>Collect volatile information</li><li>Collect non-volatile information</li><li>Memory analysis</li><li>Registry analysis</li><li>Cache, cookie, history analysis</li><li>File analysis</li><li>Metadata investigation</li><li>Event log analyis</li></ul><p>Let’s try out the tools!</p><h4>Tools 3: PsLoggedOn</h4><p>PsLoggedOn is an applet that displays both the locally logged-on users and users logged on via resources for either the local computer or <em>a remote one</em>. If you specify a user name instead of a computer, PsLoggedOn searches the computers in the network neighborhood and tells you if the user is currently logged on.</p><p>To use this, we need to run the PsLoggedOn exe file on the Windows command line. After running the exe file, we will be able to see the users that are logged on to our computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*g_z6F6hAYkwTtnfXz7PLrg.png" /><figcaption>PSLoggedOn</figcaption></figure><p>From my try-out, we can see that there is only one user that is logged in, and it’s only from the local access. I can identify that there are no other users that are logged in to my computer, either it’s from local, or from other resource shares.</p><h4>Tools 4: Access Enum</h4><p>AccessEnum gives you a full view of your file system and registry security settings in seconds, making it the ideal tool for helping you find security holes and lock down permissions where necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*YWm8XgxTyKjClfTh3wnfyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*KgShJ8OIefkLZyKtvqzbPQ.png" /><figcaption>Access Enum</figcaption></figure><p>With Access Enum, we are able to see what kind of users or group of users are able to read, write, both, or deny, on a certain Windows path. Besides that, we can also see the path properties, starting from the sharing configuration, security configuration, see the previous versions, and other configurations. Specifically on the security tab, we can see the group or user names that are granted permission for the chosen path. On the security tab also, we can edit the permission, oversee the permission for SYSTEM (full control, modify, read &amp; execute, list folder contents, read, write, and special permissions) or even see advanced permission that consists of auditing permission and effective access. In forensics, this tool is very beneficial, one of its function is to identify if a certain user did certain actions that are prohibited to that users.</p><h4>Conclusion</h4><p>Windows monitoring and forensics are essential for us to examine our Windows computer, especially towards its programs, connections, performance, etc. There are lots of tools that we can use to do Windows monitoring and forensics. Some of the tools are available through Sysinternals Suite.</p><p>So, that’s it for today’s episode, see you on another episode peeps!</p><blockquote>Writer:</blockquote><blockquote>Yonatan Jori Saputro</blockquote><blockquote>18218024</blockquote><blockquote>II4033 Digital Forensics</blockquote><blockquote>Tugas Review Tools untuk Monitoring and Forensics pada Windows</blockquote><p>Reference:</p><ul><li><a href="https://searchwindowsserver.techtarget.com/definition/Windows-Sysinternals">https://searchwindowsserver.techtarget.com/definition/Windows-Sysinternals</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3034ce522d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Forensics: is this tree fake?]]></title>
            <link>https://medium.com/@yonatanjori/image-forensics-is-this-tree-fake-15d81aa8162?source=rss-543c6cda3bc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/15d81aa8162</guid>
            <category><![CDATA[digital-forensics]]></category>
            <category><![CDATA[photo-edit]]></category>
            <category><![CDATA[forensic-image]]></category>
            <category><![CDATA[fake-photo]]></category>
            <dc:creator><![CDATA[Natan ]]></dc:creator>
            <pubDate>Sun, 03 Oct 2021 23:47:40 GMT</pubDate>
            <atom:updated>2021-10-21T14:38:44.780Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjRjjsrATD0tFk59ZH9T1g.jpeg" /><figcaption>Analyzed Image</figcaption></figure><p>See the above image. At first sight, it looks like that there is no forgery or editing done there right? At least for me, I can’t seem to think of any particular component on that image that has been edited.</p><h4>Hypothesis</h4><p>Hmm but I wonder. Since the task is from one of my uni subjects—Digital Forensics — and my lecturer specifically said that the task is to find <em>what’s wrong</em> with the picture. Henceforth, I tried to micro analyze the picture, just with my bare eyes, for now, before using any tools.</p><ol><li>The front tree</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*GQzvt26aKO3PHvfRnO5iEw.png" /><figcaption>Hypothesis on where the forgery is done: tree</figcaption></figure><p>Just for a hypothesis, with my bare eyes, I find the top or the most-front tree a bit odd and discolored compared to other trees on the image. It looks like that tree was just embedded on an already-existing image. To further explain why I hypothesized this ‘fake tree’ to be the forged component of the image, here are my reasons:</p><ol><li>Discoloration. That particular tree tends to have a different green color compared to the other tree. The saturation of that tree is likely to be higher compared to the other tree since the color is greener compared to the other tree. This can be caused by color editing on that particular area or cut and glue the extra tree to the existing image.</li><li>Edges. The edges of that tree are too sharp compared to the other trees.</li><li>Quality. It almost looks like that the mentioned tree was shot with a different camera since the quality of that tree is quite different from the other tree.</li></ol><p>I’m not a camera or image expert. But I think, all of my aforementioned points can be tackled by the fact that that tree is at the most-front, so the camera could catch it better, hence yielding the more saturated and better quality tree.</p><p>2. The back building</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*-W0Qf9YAHx3XE60rDN0v3w.png" /><figcaption>Hypothesis on where the forgery is done: building</figcaption></figure><p>Again, with my bare eyes, I find the back building a bit odd. Here are my reasons:</p><ol><li>Edges. Compared to another ‘building’ or concrete or non-tree component on the image which is the tower on the right side of the image, the edges on the back building are way clearer. The tower, from our point of view, is in the front of the back building. With that, without calculating the focus of the camera, the edges on the tower should’ve been clearer. But as you can see the tower’s edges are blurry. The edges on the back building are more clean-cut and clear.</li></ol><p>But but but but! I was so curious about what is this building? Where is it located? I was only given the image and I didn’t really know that information. With that information, perhaps, I would be able to predict better whether the image is fake or not. I used google image, search keywords by keyword “old Dutch building in Indonesia” etc. I couldn’t find it.</p><p>But I got an idea. I have a friend that’s majoring in architecture. Perhaps she knows this building only by its roof. I sent her the image. And YES. She knows what building is that.</p><blockquote>Al Ukhuwah Mosque</blockquote><p>And THAT is the ‘building’ that I was looking for. Now let’s see the resemblance between the reference ‘roof’ and the Al Ukhuwah Mosque ‘roof’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*VCoPlre_lLwNsZ5KGkPISQ.png" /><figcaption>Al Ukhuwah Mosque Roof</figcaption></figure><p>But, that’s not really the important thing here. Here is the full image of Al Ukhuwah Mosque.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*FbAJcBVJbfkv0Wcgw8uaEg.png" /><figcaption>Al Ukhuwah Mosque</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*7R81qOWkzOecn1JHoWlDbg.png" /><figcaption>Task Image vs Al Ukhuwah Mosque</figcaption></figure><p>Yep. Yep. Yep. There IS a ‘tower’ right there. So it is very possible that the “back building” is not fake. Because we can see both, the back building and the tower on the image and it is very likely that those two things are taken in one picture. With this, I think the likelihood that the back building is clipped or embedded onto an existing image is decreased.</p><p>Besides searching for the building, I wanted to also search for the plants. Is there any plant image that is exactly the same as the ones on the images? But this is very hard to do since we have tons of plant images on the internet, and we can’t narrow it down to a specific search query.</p><p>To conclude, with all that, these are my prediction on where the image was edited:</p><ol><li>The front tree. Either it’s just a color effect or manual clipped and glued to an existing image.</li><li>The overall image. There is a possibility in which the overall image is edited by using a filter for the whole image, editing the brightness, saturation, clarity, etc, or other measures.</li></ol><p>But then again, my points are just a hypothesis. There are lots of components on that image and every one of them could be the forged one.</p><h4>Trying out the tools</h4><p>To test my hypotheses, there are several tools that I can use. But even with these tools, we still have to identify each component on the image. Because until now, as far as I know, there are no tools that explicitly tell us <em>“this image is a fake on. the forgery was done on this particular component”</em>. So yes, let’s try out some tools!</p><p>By the way, I used various tools, such as <strong>Fotoforensics.com, Forensically, JPEGsnoop, Exiftool</strong>. With all that, I am just going to explain key analysis points that I got by using those tools. I will not explain to you each and every tool that I said because I think, principally, those tools are the same.</p><ol><li>Is it forged?</li></ol><p>Short answer Yes, definitely. We can see this this by uploading the image to the tools that we can use and see the source of the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*QK4o3tpeZvVRD8g4M-a82g.png" /><figcaption>Software used on the image (JPEGsnoop)</figcaption></figure><p>We can clearly see that the software used for the image is GIMP. GIMP is short for GNU Image Manipulation Program. In short, this means that the image has been edited through at least one application for image manipulation. The said software could be Adobe Photoshop, Corel Draw, or other image manipulation softwares.</p><p>Other than that, the quality of the image is also not at 100%, which means that the image quality has been intentionally decreased.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*acaDSVZ5wYEH_eFTpQyj8w.png" /><figcaption>Image quality (fotoforensics.com)</figcaption></figure><p>So we can conclude that, yes, the image has been edited intentionally.</p><p>2. Color contrast</p><p>The next thing that we can do is to look for the coloration of the image. As I mentioned earlier, the front tree is discolored, in a way that it has a significantly different color than the other trees. We can dramatize the difference of the tree by using Level Sweep in forensically.</p><p>By configuring the sweep level, width, and opacity, we can clearly see that there is a significant difference between the front tree and the rest of the tree. The saturation of the image is somehow different only on the front tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*0RdxU0lnzl1BSV9SMNewqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*rNC8qR2AEF3mcdz4OfuRmA.png" /><figcaption>Level Sweep configuration on the image (forensically)</figcaption></figure><p>With that, we have some possibilities:</p><ul><li>All of the trees are fake and manually clipped to an existing image. This is because relatively, all trees have different saturation and clarity.</li><li>Only one or individual tree is fake</li></ul><p>3. Error Level Analysis (ELA)</p><p>The first that we can analyze is the rainbowing on the image after we analyze it using ELA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*j_lqb_zFmnDvjBTr4oKI3Q.png" /><figcaption>ELA: rainbowing on the image (forensically)</figcaption></figure><p>You can see that the image contains heavy rainbowing in this case a rainbow ring. In the case of ELA and re-saved images, there may be a visible separation between the luminance and chrominance channels in the form of a blue/purple/red coloration, which is known as a rainbowing. Drawing tools like Photoshop can create surfaces with a distinct rainbow pattern that are nearly uniform in color.</p><p>In general, Photoshop and other Adobe products produce a large number of rainbow colors. However, the rainbow is not an artifact unique to Adobe products. For example, the open-source GIMP program produces few rainbow colors, and some high-quality camera photos may also contain rainbow colors across uniformly colored surfaces, such as white walls or blue skies. Some drawing tools, such as Microsoft’s Paint, do not produce rainbow colors. The strong presence of rainbow colors only suggests that an Adobe product such as Photoshop or Lightroom was used to save the image. It does not identify intentional modifications.</p><p>The next thing that we can analyze is of course the error level itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*8QKKUcH1BoKdp89_k5WffQ.png" /><figcaption>ELA: error level on the image</figcaption></figure><p>Similar edges should have a similar brighness on the ELA result. All high-contrast edges should look similar, and all low-contrast edges should look similar. In an original photo, low-contrast edges should be almost as bright as high-contrast edges. Besides that, regardless of the actual color of the surface, all flat surfaces should have about the same coloring under ELA.</p><p>That is not the case for the image that we have. We can clearly see that the edges on the front tree is relatively different compared to the rest of the image. Other than that the surface of the front tree doesn&#39;t have the same coloring under ELA. So, even after excluding the coloration of the image, with ELA we can tend to see that the front tree is quite different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*Xe45kMoF_nEtQ-fvRXJZcQ.png" /><figcaption>Oddness at the bottom right of the image</figcaption></figure><p>Other than that, if we look up close on the ELA image, we can find something odd on the bottom down right of the image. Supported by also analyzing the coloration of the image, we can clearly see the error on the bottom right of the image. Why is there a sudden different color on the trees? This is likely because there are some clonings that were done on this image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*CRnLrRggjMsTNjTCmCk-aA.png" /><figcaption>Principal component analysis-distance (forensically)</figcaption></figure><p>By using principal component analysis, with the component of distance, we can also see that the front tree is at different clarity or sharpness compared to the rest of the image. This is possible because of the clipped and glued a different image (in this case the front tree), or just because it is at the front of the image so that the camera could capture it better.</p><h4>Conclusion</h4><p>As far as I know, there are no specific tools that can tell us “the forged component of the image is ‘this part of the image’”. Or in other words, we have to analyze component by component, using methods by methods, to see or predict which component of the image is forged.</p><p>For the analysis that I did for this particular image, there are several doubts about where the image was forced. One thing that we know <em>for sure</em> is that the image was forged, because of the rainbowing, GIMP use, etc. But we’re not sure where and how it was forged.</p><p>The building and tower are most likely not forged as we can find the real ‘building and tower’ and they are close to each other so that it is a real possibility that the two brick-and-mortar was captured on one image.</p><p>So, we’re focusing on the trees and overall image edit. After all the analysis and tools use, here are some of my predictions on where the image was forged:</p><ul><li>All the trees on the image are clipped and glued onto an existing image. If not, the trees were forged by clonings, discoloration, and other methods.</li><li>Only the front tree on the image is clipped and glued onto an existing image.</li><li>Filter usage on the image, such as making the image more low-saturated.</li></ul><p>But then again, I’m no digital forensic expert or specifically digital image forensic expert. Those are only my predictions. I would love to hear your analysis too on the image! You can find the image <a href="https://drive.google.com/file/d/1Kklu2BQrCP9yxI1Ixu00dLdIaNGS1irh/view?usp=sharing">here</a>. Let’s analyze the image🧐!</p><p>Writer:</p><p>Yonatan Jori Saputro</p><p>18218024</p><p>II4033 Digital Forensics</p><p>Forensik Gambar</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15d81aa8162" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Injection — DVWA: fetching the not-supposed-to-be-fetched data]]></title>
            <link>https://medium.com/@yonatanjori/sql-injection-dvwa-fetching-the-not-supposed-to-be-fetched-data-fa772fa935f6?source=rss-543c6cda3bc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa772fa935f6</guid>
            <category><![CDATA[sql-injection]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[dvwa]]></category>
            <category><![CDATA[digital-forensics]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Natan ]]></dc:creator>
            <pubDate>Sun, 26 Sep 2021 19:23:47 GMT</pubDate>
            <atom:updated>2021-10-21T14:39:24.970Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL Injection - DVWA: fetching the not-supposed-to-be-fetched data</h3><h4>DVWA — Testing SQL Injection Vulnerability</h4><p>DVWA stands for Damn Vulnerable Web App, which means a web application that provides security holes that are intentionally created to test someone’s hacking abilities. In other words, DVWA is a hacking target.</p><p>DVWA&#39;s main goals are to help security professionals test their skills and tools in a legal environment, help web developers better understand web application protection processes, and help teachers/students learn web application security in a classroom environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*A-p8csjXSG5MAPfnf-iNrQ.png" /><figcaption>SQL Injection Illustration (<a href="https://portswigger.net/">https://portswigger.net/</a>)</figcaption></figure><p>There are lots of DVWA attacks. But for now, I will explain more on the SQL injection (manual) attack. SQL injection (SQL fishing) is a technique that is widely used to attack data-driven applications. SQL injection is done by inserting parts of SQL statements into an input field to induce the website to pass a newly formed malicious SQL command to the database. SQL injection is a code injection technique that exploits a security vulnerability in application software. This vulnerability occurs when user input is incorrectly filtered for string literal escape characters embedded in SQL statements, or user input is not typed strictly and runs unexpectedly.</p><h4>How does SQL injection vulnerability work (via DVWA)</h4><p>For now, I’m going to try out the Low-security level of SQL injection. So, in order to do that, I changed the security level on the DVWA dashboard into the low-level.</p><p>Soooo, what is actually the goal of this SQL injection vulnerability testing you might ask🧐. Basically what we’re going to <em>try </em>to do is to <em>steal </em>users’ passwords, avatars, and other users’ credentials that are saved on the database. That’s interesting right! Let’s get on with it now.</p><p>Using the source that’s availbale on the DVWA platform, here is the source of the low level SQL injection that we’re going to play with.</p><pre>&lt;?php<br><br>if( isset( $_REQUEST[ &#39;Submit&#39; ] ) ) {<br>    // Get input<br>   <strong> $id = $_REQUEST[ &#39;id&#39; ];<br></strong><br>    // Check database<br>    <strong>$query  = &quot;SELECT first_name, last_name FROM users WHERE user_id = &#39;$id&#39;;&quot;;</strong><br>    $result = mysqli_query($GLOBALS[&quot;___mysqli_ston&quot;],  $query ) or die( &#39;&lt;pre&gt;&#39; . ((is_object($GLOBALS[&quot;___mysqli_ston&quot;])) ? mysqli_error($GLOBALS[&quot;___mysqli_ston&quot;]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . &#39;&lt;/pre&gt;&#39; );<br><br>    // Get results<br>    while( $row = mysqli_fetch_assoc( $result ) ) {<br>        // Get values<br>        <strong>$first = $row[&quot;first_name&quot;];<br>        $last  = $row[&quot;last_name&quot;];</strong><br><br>        // Feedback for end user<br>        <strong>echo &quot;&lt;pre&gt;ID: {$id}&lt;br /&gt;First name: {$first}&lt;br /&gt;Surname: {$last}&lt;/pre&gt;&quot;;</strong><br>    }<br><br>    mysqli_close($GLOBALS[&quot;___mysqli_ston&quot;]);<br>}<br><br>?&gt;</pre><p>As you can see on the code, essentially, they asked for a userid.</p><pre>$id = $_REQUEST[ &#39;id&#39; ];</pre><p>And then from there, the ‘website’ is going to show you or send the needed data, which are supposedly the first name and the last name of the user.</p><pre>$query  = &quot;SELECT first_name, last_name FROM users WHERE user_id = &#39;$id&#39;;&quot;;</pre><p>But, this is a vulnerability. Why? Becuase the very nature of SQL commands are continuous and can be mixed with other SQL commands. As you can see on the query code, it’s written like this:</p><pre>user_id = &#39;<strong>$id</strong>&#39;;&quot;;</pre><p>On that very code, we can fill the <strong>‘$id’</strong> with another SQL command, because again, SQL command are basically continuous. It’s a possibility in SQL, where we can write a command like this:</p><pre>SELECT A FROM B WHERE C = <strong>D UNION SELECT E,F FROM G;</strong></pre><p>From that example, we can see how the SQL commands are vulnerable. From the previous request query, we can substitute the <strong>‘$id’ </strong>with extra queries like the <strong>‘D UNION SELECT E,F FROM G’</strong>. And from there, essentially, we can look for other users’ data, other the already-defined needed data (eg. first_name, last_name, or ‘A’).</p><p>So, yes, SQL injection basically works by exploiting the fact that there are no validation on the request query and the fact that SQL commands work continuously.</p><h4>How can we avoid this vulnerability explotation?</h4><p>Well, the short answer is to add some sort of validation when we ask for the ‘<strong>$id’ </strong>on the request query.</p><p>By adding some sort of validation, we can avoid the exploitation of the continous nature of SQL commands. The validation can be vary. The validations were to be implemented on the web code or query request code, or in this case (adjusting to the source provided by DVWA), on the PHP code. With the validation, we can make sure that only the correct input is processed to fetch the necessary data. Here are some of my ideas:</p><ul><li>Integer validation</li></ul><p>Adding a validation to make sure the input value is an integer. A user id, usually, is an integer. So, by adding an integer validation, we can avoid strings, which will essentially be a SQL commands, to be used on the user id input value.</p><p>Here’s a possible algorithmic notation:</p><pre>while <strong>not isInteger(id)</strong><br>    do Read(id)</pre><p>On PHP sytax (only a part of the full code), we can utilize is_int() function that is provided by the PHP module:</p><pre>while (<strong>!is_int($id)</strong>){<br>// Get input<br>    echo &quot;Invalid user id, please reinput a correct user id.&quot;;   <br>    $id = $_REQUEST[ &#39;id&#39; ];<br>}</pre><ul><li>Exists in the database validation</li></ul><p>Adding a validation to make sure the input value exists in the database. A user id, even though it’s uncommon, can be a string. So te possible validation that we can do in order to check the input value is correct and valid is to check whether it’s available/exist in the user database or not.</p><p>Here’s a possible algorithmic notation:</p><pre>while not (<strong>id exists in database</strong>)<br>    do Read(id)</pre><p>On PHP sytax (only a part of the full code), we can make a function to match and check whether the input user id value is valid:</p><pre>function isAvailable($id) {<br>    <strong>$query  = &quot;SELECT user_id FROM users;&quot;;</strong><br>    $result = mysqli_query($GLOBALS[&quot;___mysqli_ston&quot;],  $query ) or die( &#39;&lt;pre&gt;&#39; . ((is_object($GLOBALS[&quot;___mysqli_ston&quot;])) ? mysqli_error($GLOBALS[&quot;___mysqli_ston&quot;]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . &#39;&lt;/pre&gt;&#39; );</pre><pre>    <strong>$valid = false<br>    while( $row = mysqli_fetch_assoc( $result ) &amp;&amp; !$valid) {<br>        $userid = $row[&quot;user_id&quot;];</strong></pre><pre><strong>        if ($id == $userid) {<br>            $valid = true<br>        }<br>    }<br>    return $valid</strong><br>}</pre><pre>while (<strong>!isAvailable($id)</strong>){<br>// Get input<br>    echo &quot;Invalid user id, please reinput a correct user id.&quot;;   <br>    $id = $_REQUEST[ &#39;id&#39; ];<br>}</pre><p>As you can see, on the code, I validate whether the input $id is availble on the $row or the fetched user id from the database.</p><h4>Trying it out: testing the vulnerabilities</h4><p>Now, we can go test the SQL injection vulnerability with the DVWA. Now if we go to the <strong>SQL Injection</strong> menu on the DVWA navigation bar, we will be redirected to a page like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*Sr2wQEvvmWfPkivR9uJiaw.png" /><figcaption>DVWA SQL Injection Vulnerability Attack Test Page</figcaption></figure><p>We’re asked to input a user id. From my previous explanation, we know that we can attack this field by inputing extra commands to fetch another data that are supposedly not fetch-able. But before that we can try other things too.</p><ol><li><strong>Normal value</strong></li></ol><p>On the normal value one, we can just input the most expected value to the field. The most expected values are of course an available and direct user id, such as ‘1’ or ‘2’, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*U-zoj9knBEgJrfNph_GxRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*We0pOJLRYbR_Uq_NTVHZnw.png" /><figcaption>Normal Value Examples</figcaption></figure><p>As you can see, the return values are all as expected. It yields normal first name and surname, since we only put ‘1’ and ‘2’ on the field.</p><p><strong>2. Always-true value</strong></p><p>What I mean by an always-true value is when we can input a condition in which it’s always true. By doing that, we can fetch all data that exist on the database. Always-true value can be as simple as ‘<strong>1’ = ‘1’</strong>, which will always be true.</p><p>In order to exploit this vulnerability, we have to configure what should we put on the field. On the code source we know that it’s written:</p><pre>$query  = &quot;SELECT first_name, last_name FROM users WHERE user_id = <strong>&#39;<em>$id</em>&#39;</strong>;&quot;;</pre><p>We need to look deeper into the apostrophes. In order to make sure the query works, we have to make an adequate query as well. We can change the <strong>$id</strong> into another value that can fulfill the query. For example, with embedding the ‘<strong>1’ = ‘1’</strong>, we can substitute the <strong>$id</strong> with <strong>1&#39; or ‘1’ = ‘1</strong> . That example works because the apostrophes are in the right amount and position, so the query will be:</p><pre>$query  = &quot;SELECT first_name, last_name FROM users WHERE user_id = &#39;<strong><em>1&#39; or &#39;1&#39;= &#39;1</em></strong>&#39;<strong>;&quot;;</strong></pre><p>By using <strong>1&#39; or ‘1’ = ‘1 </strong>as the <strong>$id </strong>value, we will be able to fetch all first_name and last_name on the database. This is possible since on the user id WHERE clause I use OR operator and a definite TRUE condition. So the result will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*Dl5toqvk9z0truKHyg_7HA.png" /><figcaption>Always True Value Example</figcaption></figure><p><strong>3. Fetch another data</strong></p><p>On the last ‘attack’, now not only can we fetch the data of multiple users, we also will be able to fetch another data that are supposed not to be fetchable, as those are confidential.</p><p>This can be done for example by utilizing UNION clause on the SQL command. So after the WHERE clause on the defined SQL command (on the code/source), on the <strong>$id</strong> we can write another SQL command there, in which we can utilize UNION clause.</p><p>For example, we can use</p><pre><strong>‘ UNION SELECT user, password FROM users# </strong></pre><p>With that, I substitute the <strong>$id </strong>with <strong>‘ UNION SELECT user, password FROM users# </strong>, which will will change the request to the database into:</p><pre>$query  = &quot;SELECT first_name, last_name FROM users WHERE user_id = &#39;<em>&#39; </em><strong><em>UNION SELECT user, password FROM users</em>&#39;;&quot;;</strong></pre><p>On the first half of that SQL command</p><pre>$query  = &quot;SELECT first_name, last_name FROM users WHERE user_id = &#39;<em>&#39;</em></pre><p>, we won’t receive anything since the are no record on the database that fulfills the WHERE clause user_id = ‘’. But on the second half of the SQL command,</p><pre><strong><em>UNION SELECT user, password FROM users</em>&#39;;&quot;;</strong></pre><p>, we will receive all user and password from the users table. So yes, we will receive the user_id and their password, which are essentially not the supposed and destined data: first_name and last_name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*ugnpKu6LSMYn3Hjfig65sw.png" /><figcaption>Fetch Another Data Example</figcaption></figure><p>Since it uses UNION, the name of the attribute will follow the first SQL command, in this case first_name and last_name. So, this won’t cause an error for the next code which is:</p><pre>while( $row = mysqli_fetch_assoc( $result ) ) {<br>        // Get values<br>        <strong>$first = $row[&quot;first_name&quot;];<br>        $last  = $row[&quot;last_name&quot;];</strong></pre><p>, since we still have [“first_name”] and [“last_name”].</p><p>From the fetched password, we can directly know the password of each user that is on the database. Let’s say that we want to know gordonb’s password. We can simply copy and paste the password into a decrypting tool and gain the information.</p><pre>e99a18c428cb38d5f260853678922e03</pre><p>We can decrypt the password utilizing a decryption tool. But first we have to know what kind of encryption was used. We can utilize a prediction tool (for example <a href="https://www.dcode.fr/cipher-identifier">https://www.dcode.fr/cipher-identifier</a>). From there we can see that MD5 was used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*XW6aRaA5R2g0L--vymFJcw.png" /><figcaption>Encryption Method Detection</figcaption></figure><p>From there, we can use a decryption tool and find that the original password is <strong>abc123.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*rwmhnwcjfJoZxwnK7J8P9w.png" /><figcaption>Gordonb’s Password</figcaption></figure><p>See. It is <em>that </em>easy to find gordonb’s password.</p><p>We also need to make sure that the amount of attribute/column that we use on the ‘attack’ SQL command matches the one that is on the code. In this example, there are two attributes: first_name ($first, First name) and last_name ($last, Surname):</p><pre>while( $row = mysqli_fetch_assoc( $result ) ) {<br>        // Get values<br>        <strong>$first = $row[&quot;first_name&quot;];<br>        $last  = $row[&quot;last_name&quot;];</strong><br><br>        // Feedback for end user<br>       <strong> </strong>echo &quot;&lt;pre&gt;ID: {$id}&lt;br /&gt;<strong>First name: {$first}</strong>&lt;br /&gt;<strong>Surname: {$last}</strong>&lt;/pre&gt;&quot;;</pre><p>So, in one go, we can only fetch two kind of data, for example that I used previously: user and password. We can also see or use another data, for example user and avatar, user and last_login, with these inputs:</p><p>For user and avatar</p><pre><strong>‘ UNION SELECT user, avatar FROM users#</strong></pre><p>With the result of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*LhCk9n1UzUSmrkhBCfUqPw.png" /><figcaption>User and Last Login Data Fetching</figcaption></figure><p>From there, we can see the users’ avatar, for example, if we look at gordonb’s avatar, we will find his avatar. This is also dangerous since a profile picture can contain a person’s face, which is a private data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*awQG0QYLUJbWjzkWhwZF9Q.png" /><figcaption>Gordonb’s Avatar</figcaption></figure><p>For user and last login</p><pre><strong>‘ UNION SELECT user, last_login FROM users#</strong></pre><p>With the result of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*2NdJeSXIz1sEZD-8XdyBjw.png" /><figcaption>User and Last Login Data Fetching</figcaption></figure><p>The explanation on how all that works are basically the same with the user-password data fetching.</p><p>Notice how on the ‘UI’ of the yielded PHP code we always see ‘First name:’ and ‘Surname:’ but with different values. It’s because it’s the code on the source code, as I mentioned earlier.</p><pre>while( $row = mysqli_fetch_assoc( $result ) ) {<br>        // Get values<br>        <strong>$first = $row[&quot;first_name&quot;];<br>        $last  = $row[&quot;last_name&quot;];</strong><br><br>        // Feedback for end user<br>       <strong> </strong>echo &quot;&lt;pre&gt;ID: {$id}&lt;br /&gt;<strong>First name: {$first}</strong>&lt;br /&gt;<strong>Surname: {$last}</strong>&lt;/pre&gt;&quot;;</pre><p>I only change the data on the <strong>$first </strong>and <strong>$last </strong>or essentially changed the fetched data on the <strong>[“first_name”] </strong>and<strong> [“last_name”]</strong>. With that, the printed values will differ based on what data are being fetched.</p><h4>Trying it out: protecting the vulnerabilities</h4><p>As I mentioned on the previous chapter, there are lots of ways on how can we protect the SQL injection vulnerabilities. One of the said many ways is adding validation after the user inputs the user id. The validation can also be vary. For now, it can be <strong>integer validation</strong> and <strong>exists in database validation</strong>.</p><p>Adjusting to the PHP language of the source code example, here is the possible added function and validation to the source code:</p><pre>function isValid($id) {<br>    // Is the input user id an integer<br>    if (<strong>is_int($id)</strong>) {<br>        <strong>$valid = true</strong><br>    }</pre><pre>    // Is the input user id exists in the database<br>    <strong>$query  = &quot;SELECT user_id FROM users;&quot;;</strong><br>    $result = mysqli_query($GLOBALS[&quot;___mysqli_ston&quot;],  $query ) or die( &#39;&lt;pre&gt;&#39; . ((is_object($GLOBALS[&quot;___mysqli_ston&quot;])) ? mysqli_error($GLOBALS[&quot;___mysqli_ston&quot;]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . &#39;&lt;/pre&gt;&#39; );</pre><pre><strong>    $valid = false<br>    while( $row = mysqli_fetch_assoc( $result ) &amp;&amp; !$valid) {<br>        $userid = $row[&quot;user_id&quot;];</strong></pre><pre><strong>        if ($id == $userid) {<br>            $valid = true<br>        }<br>    }<br>return $valid</strong><br>}</pre><pre>while (<strong>!isvalid($id)</strong>){<br>// Get input<br>    echo &quot;Invalid user id, please reinput a correct user id.&quot;;   <br>    $id = $_REQUEST[ &#39;id&#39; ];<br>}</pre><p>I put the two validations under one function. However we can put the two into two different function and even only use one of the function, but then again we have to see how the database is configured and how is the user id on the database configured.</p><p>So, on the final code we can finally have a source code that is more or less like this:</p><pre>&lt;?php<br><br>if( isset( $_REQUEST[ &#39;Submit&#39; ] ) ) {<br>    // Get input<br>   <strong> $id = $_REQUEST[ &#39;id&#39; ];</strong></pre><pre>    function isValid($id) {<br>        // Is the input user id an integer<br>        if (<strong>is_int($id)</strong>) {<br>            <strong>$valid = true</strong><br>        }</pre><pre>        // Is the input user id exists in the database<br>        <strong>$query  = &quot;SELECT user_id FROM users;&quot;;</strong><br>        $result = mysqli_query($GLOBALS[&quot;___mysqli_ston&quot;],  $query ) or die( &#39;&lt;pre&gt;&#39; . ((is_object($GLOBALS[&quot;___mysqli_ston&quot;])) ? mysqli_error($GLOBALS[&quot;___mysqli_ston&quot;]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . &#39;&lt;/pre&gt;&#39; );</pre><pre><strong>        $valid = false<br>        while( $row = mysqli_fetch_assoc( $result ) &amp;&amp; !$valid) {<br>            $userid = $row[&quot;user_id&quot;];</strong></pre><pre><strong>            if ($id == $userid) {<br>                $valid = true<br>            }<br>        }<br>        return $valid</strong><br>    }</pre><pre>    // Validation<br>    while (<strong>!isvalid($id)</strong>){<br>    // Get input<br>        echo &quot;Invalid user id, please reinput a correct user id.&quot;;   <br>        $id = $_REQUEST[ &#39;id&#39; ];<br>    }</pre><pre>    // Check database<br>    <strong>$query  = &quot;SELECT first_name, last_name FROM users WHERE user_id = &#39;$id&#39;;&quot;;</strong><br>    $result = mysqli_query($GLOBALS[&quot;___mysqli_ston&quot;],  $query ) or die( &#39;&lt;pre&gt;&#39; . ((is_object($GLOBALS[&quot;___mysqli_ston&quot;])) ? mysqli_error($GLOBALS[&quot;___mysqli_ston&quot;]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . &#39;&lt;/pre&gt;&#39; );<br><br>    // Get results<br>    while( $row = mysqli_fetch_assoc( $result ) ) {<br>        // Get values<br>        <strong>$first = $row[&quot;first_name&quot;];<br>        $last  = $row[&quot;last_name&quot;];</strong><br><br>        // Feedback for end user<br>        <strong>echo &quot;&lt;pre&gt;ID: {$id}&lt;br /&gt;First name: {$first}&lt;br /&gt;Surname: {$last}&lt;/pre&gt;&quot;;</strong><br>    }<br><br>    mysqli_close($GLOBALS[&quot;___mysqli_ston&quot;]);<br>}<br><br>?&gt;</pre><p>Even though the explanations that I give here perhaps is not the most complete explanation. I sure do hope that we can learn a thing or two, espcially about SQL injection and how can we protect ourselves, escpecially perhaps as a web developer, from these possible SQL injection vulnerability attacks.</p><p>Thank you so so much for reading this blog or article. See you on my next journey!</p><p>Writer:</p><p>Yonatan Jori Saputro</p><p>18218024</p><p>II4033 Digital Forensics</p><p>Tugas 2: DVWA White Boxing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa772fa935f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transferring Read Weather Data into A Database and Showing It to A Webpage with ESP32 and BME280]]></title>
            <link>https://medium.com/@yonatanjori/transferring-read-weather-data-into-a-database-and-showing-it-to-a-webpage-with-esp32-and-bme280-5dd6a89caafd?source=rss-543c6cda3bc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dd6a89caafd</guid>
            <category><![CDATA[bme]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Natan ]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 06:16:04 GMT</pubDate>
            <atom:updated>2020-04-26T12:59:36.492Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey, cross-over episode on this experiment! I learned about database on another lecture called Database Modelling and Database Management in my uni, and the interesting part is that, on today’s experiment we’re going to utilize a database system. I used to ‘play’ with MySQL database, so perhaps this won’t be too hard for me, as this experiment will utizile MySQL. In a nutshell this experiment is the use of ESP32 and Arduino IDE to insert data into a MySQL database that can be accessed through a domain or hosting account.</p><p>On this story, I am just going to explain to you this experiment theoretically, as I previously stated on my previous story, I don’t have enough tools and resources to do this experiment, so I really hope I can gather with my teammates to do this experiment or until this pandemic is settled then I can buy a BME280.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*g_HFk1Pk7n4W-2dL" /><figcaption>Experiment Preview</figcaption></figure><p>So, this is basically how the system works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*uOPtMJhn5XfwKXmr" /><figcaption>System Chart/Flow</figcaption></figure><p>As you can see, ESP32 will behave like a access point/server, and then PHP script will be used to publish sensor reading to a relation in database and to publish the table into a hosting account.</p><h4>Tools</h4><p>Here are the needed tools, the tools that I don’t have :(</p><ol><li>ESP32</li><li>BME280</li><li>Jumper cables</li><li>Breadboard</li><li>Arduino IDE</li><li>Hosting server and domain name</li><li>PHP script to insert data into MySQL</li><li>PHP script to display a MySQL table on a webpage</li><li>MySQL database</li></ol><p>Physically there is no new tools, but there are several new kit/tech tools that we have to provide as you can see on the list above such as hosting server, domain name, PHP scripts, and MySQL database. But also don’t forget to install the Adafruit Library (BME280 and Unified Sensor)</p><h4>Wiring</h4><p>The wiring is basically the same as previous experiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*o8SFAiKOrAxL3gjF" /><figcaption>Wiring Configuration</figcaption></figure><h4>Hosting Account</h4><p>This hosting account will be used for PHP application and MySQL database.</p><p>Accessibility is one main feature that we would like to bring up on this experiment, so a hosting account is very important. We have to buy a hosting service and a domain name (on how to make one check <a href="https://my.bluehost.com/hosting/help/choosing-a-domain-name">this</a>). After setting up a domain name, go to cPanel &gt; MySQL Database Wizard {cPanel is a web hosting control panels, displaying metrics about our server and allowing various modules such as file, database, preferences, web app, etc}. After that create a new database in which we’ll save the read data from ESP32, then set up a username also password to access the database (if you feel like so).</p><h4>MySQL Table</h4><p>If you use Blueocean as your hosting account and cPanel to set and manage it, go to phpMyAdmin to create a new SQL table to store out weather data. Go to the said database then name it according to your preferences (eg. example_esp_data), then go to the SQL tab and run this query: (this query will create a new table with the name of your preferences (previously set))</p><pre>CREATE TABLE SensorData (<br>    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,<br>    sensor VARCHAR(30) NOT NULL,<br>    location VARCHAR(30) NOT NULL,<br>    value1 VARCHAR(10),<br>    value2 VARCHAR(10),<br>    value3 VARCHAR(10),<br>    reading_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP<br>)</pre><h4>PHP Script to Insert Data to MySQL</h4><p>With cPanel in our usage, to create a PHP script that has the ability to receive request from ESP32 to insert data into database, go to File Manager &gt; public_html and create a new file under the name of your willing (eg. post-esp-data.php). Then code this code, remember to replace $usernam, $password, and $dbname variables according to yours:</p><pre>&lt;?php</pre><pre>$servername = &quot;localhost&quot;;<br><br>// REPLACE with your Database name<br>$dbname = &quot;REPLACE_WITH_YOUR_DATABASE_NAME&quot;;<br>// REPLACE with Database user<br>$username = &quot;REPLACE_WITH_YOUR_USERNAME&quot;;<br>// REPLACE with Database user password<br>$password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;<br><br>// Keep this API Key value to be compatible with the ESP32 code provided in the project page. <br>// If you change this value, the ESP32 sketch needs to match<br>$api_key_value = &quot;tPmAT5Ab3j7F9&quot;;<br><br>$api_key= $sensor = $location = $value1 = $value2 = $value3 = &quot;&quot;;<br><br>if ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;) {<br>    $api_key = test_input($_POST[&quot;api_key&quot;]);<br>    if($api_key == $api_key_value) {<br>        $sensor = test_input($_POST[&quot;sensor&quot;]);<br>        $location = test_input($_POST[&quot;location&quot;]);<br>        $value1 = test_input($_POST[&quot;value1&quot;]);<br>        $value2 = test_input($_POST[&quot;value2&quot;]);<br>        $value3 = test_input($_POST[&quot;value3&quot;]);<br>        <br>        // Create connection<br>        $conn = new mysqli($servername, $username, $password, $dbname);<br>        // Check connection<br>        if ($conn-&gt;connect_error) {<br>            die(&quot;Connection failed: &quot; . $conn-&gt;connect_error);<br>        } <br>        <br>        $sql = &quot;INSERT INTO SensorData (sensor, location, value1, value2, value3)<br>        VALUES (&#39;&quot; . $sensor . &quot;&#39;, &#39;&quot; . $location . &quot;&#39;, &#39;&quot; . $value1 . &quot;&#39;, &#39;&quot; . $value2 . &quot;&#39;, &#39;&quot; . $value3 . &quot;&#39;)&quot;;<br>        <br>        if ($conn-&gt;query($sql) === TRUE) {<br>            echo &quot;New record created successfully&quot;;<br>        } <br>        else {<br>            echo &quot;Error: &quot; . $sql . &quot;&lt;br&gt;&quot; . $conn-&gt;error;<br>        }<br>    <br>        $conn-&gt;close();<br>    }<br>    else {<br>        echo &quot;Wrong API Key provided.&quot;;<br>    }<br><br>}<br>else {<br>    echo &quot;No data posted with HTTP POST.&quot;;<br>}<br><br>function test_input($data) {<br>    $data = trim($data);<br>    $data = stripslashes($data);<br>    $data = htmlspecialchars($data);<br>    return $data;<br>}</pre><p>Say the domain is example-domain.com, so if you go to http://example-domain.com/post-esp-data.php , it’ll show you something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*Kjs0n5C2DrW_OWk7" /><figcaption>PHP Script Run on a Hosting Domain</figcaption></figure><h4>PHP Script to Display Database Content</h4><p>Continuing the cycle, the next thing to do is making a PHP script to display the database content to a webpage. The steps nearly the same as previous, create a new PHP file under the name esp-data.php for example in the /public_html directory. After that, code this code into the said file, remember don’t forget to change $username, $password, and $dbname:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;&lt;body&gt;<br>&lt;?php<br><br>$servername = &quot;localhost&quot;;<br><br>// REPLACE with your Database name<br>$dbname = &quot;REPLACE_WITH_YOUR_DATABASE_NAME&quot;;<br>// REPLACE with Database user<br>$username = &quot;REPLACE_WITH_YOUR_USERNAME&quot;;<br>// REPLACE with Database user password<br>$password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;<br><br>// Create connection<br>$conn = new mysqli($servername, $username, $password, $dbname);<br>// Check connection<br>if ($conn-&gt;connect_error) {<br>    die(&quot;Connection failed: &quot; . $conn-&gt;connect_error);<br>} <br><br>$sql = &quot;SELECT id, sensor, location, value1, value2, value3, reading_time FROM SensorData ORDER BY id DESC&quot;;<br><br>echo &#39;&lt;table cellspacing=&quot;5&quot; cellpadding=&quot;5&quot;&gt;<br>      &lt;tr&gt; <br>        &lt;td&gt;ID&lt;/td&gt; <br>        &lt;td&gt;Sensor&lt;/td&gt; <br>        &lt;td&gt;Location&lt;/td&gt; <br>        &lt;td&gt;Value 1&lt;/td&gt; <br>        &lt;td&gt;Value 2&lt;/td&gt;<br>        &lt;td&gt;Value 3&lt;/td&gt; <br>        &lt;td&gt;Timestamp&lt;/td&gt; <br>      &lt;/tr&gt;&#39;;<br> <br>if ($result = $conn-&gt;query($sql)) {<br>    while ($row = $result-&gt;fetch_assoc()) {<br>        $row_id = $row[&quot;id&quot;];<br>        $row_sensor = $row[&quot;sensor&quot;];<br>        $row_location = $row[&quot;location&quot;];<br>        $row_value1 = $row[&quot;value1&quot;];<br>        $row_value2 = $row[&quot;value2&quot;]; <br>        $row_value3 = $row[&quot;value3&quot;]; <br>        $row_reading_time = $row[&quot;reading_time&quot;];<br>        // Uncomment to set timezone to - 1 hour (you can change 1 to any number)<br>        //$row_reading_time = date(&quot;Y-m-d H:i:s&quot;, strtotime(&quot;$row_reading_time - 1 hours&quot;));<br>      <br>        // Uncomment to set timezone to + 4 hours (you can change 4 to any number)<br>        //$row_reading_time = date(&quot;Y-m-d H:i:s&quot;, strtotime(&quot;$row_reading_time + 4 hours&quot;));<br>      <br>        echo &#39;&lt;tr&gt; <br>                &lt;td&gt;&#39; . $row_id . &#39;&lt;/td&gt; <br>                &lt;td&gt;&#39; . $row_sensor . &#39;&lt;/td&gt; <br>                &lt;td&gt;&#39; . $row_location . &#39;&lt;/td&gt; <br>                &lt;td&gt;&#39; . $row_value1 . &#39;&lt;/td&gt; <br>                &lt;td&gt;&#39; . $row_value2 . &#39;&lt;/td&gt;<br>                &lt;td&gt;&#39; . $row_value3 . &#39;&lt;/td&gt; <br>                &lt;td&gt;&#39; . $row_reading_time . &#39;&lt;/td&gt; <br>              &lt;/tr&gt;&#39;;<br>    }<br>    $result-&gt;free();<br>}<br><br>$conn-&gt;close();<br>?&gt; <br>&lt;/table&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Then, if you access the same domain as previous but with different directory (http://example-domain.com/esp-data.php for example), it will show you something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/0*ZF7qITbgW9YnxlUg" /><figcaption>New PHP Script Run on a Hosting Domain</figcaption></figure><h4>Code</h4><p>After all of the configuration are set, code this on Arduino IDE, and as perusal don’t forget to change the ssid and password variables according to your WiFi credentials, besides that change the serverName variable into the URL of your PHP script that soon will receive ESP32’s request (in my case it is http://example-domain.com/post-esp-data.php ) :</p><pre>#include &lt;WiFi.h&gt;<br>#include &lt;HTTPClient.h&gt;<br>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_Sensor.h&gt;<br>#include &lt;Adafruit_BME280.h&gt;<br><br>#ifdef ESP32<br>  #include &lt;WiFi.h&gt;<br>  #include &lt;HTTPClient.h&gt;<br>#endif<br><br>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_Sensor.h&gt;<br>#include &lt;Adafruit_BME280.h&gt;<br><br>// Replace with your network credentials<br>const char* ssid     = &quot;REPLACE_WITH_YOUR_SSID&quot;;<br>const char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;<br><br>// REPLACE with your Domain name and URL path or IP address with path<br>const char* serverName = &quot;http://example.com/post-esp-data.php&quot;;<br><br>// Keep this API Key value to be compatible with the PHP code provided in the project page. <br>// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key <br>String apiKeyValue = &quot;tPmAT5Ab3j7F9&quot;;<br><br>String sensorName = &quot;BME280&quot;;<br>String sensorLocation = &quot;Office&quot;;<br><br>/*#include &lt;SPI.h&gt;<br>#define BME_SCK 18<br>#define BME_MISO 19<br>#define BME_MOSI 23<br>#define BME_CS 5*/<br><br>#define SEALEVELPRESSURE_HPA (1013.25)<br><br>Adafruit_BME280 bme;  // I2C<br>//Adafruit_BME280 bme(BME_CS);  // hardware SPI<br>//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK);  // software SPI<br><br>void setup() {<br>  Serial.begin(115200);<br>  <br>  WiFi.begin(ssid, password);<br>  Serial.println(&quot;Connecting&quot;);<br>  while(WiFi.status() != WL_CONNECTED) { <br>    delay(500);<br>    Serial.print(&quot;.&quot;);<br>  }<br>  Serial.println(&quot;&quot;);<br>  Serial.print(&quot;Connected to WiFi network with IP Address: &quot;);<br>  Serial.println(WiFi.localIP());<br><br>  // (you can also pass in a Wire library object like &amp;Wire2)<br>  bool status = bme.begin(0x76);<br>  if (!status) {<br>    Serial.println(&quot;Could not find a valid BME280 sensor, check wiring or change I2C address!&quot;);<br>    while (1);<br>  }<br>}<br><br>void loop() {<br>  //Check WiFi connection status<br>  if(WiFi.status()== WL_CONNECTED){<br>    HTTPClient http;<br>    <br>    // Your Domain name with URL path or IP address with path<br>    http.begin(serverName);<br>    <br>    // Specify content-type header<br>    http.addHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);<br>    <br>    // Prepare your HTTP POST request data<br>    String httpRequestData = &quot;api_key=&quot; + apiKeyValue + &quot;&amp;sensor=&quot; + sensorName<br>                          + &quot;&amp;location=&quot; + sensorLocation + &quot;&amp;value1=&quot; + String(bme.readTemperature())<br>                          + &quot;&amp;value2=&quot; + String(bme.readHumidity()) + &quot;&amp;value3=&quot; + String(bme.readPressure()/100.0F) + &quot;&quot;;<br>    Serial.print(&quot;httpRequestData: &quot;);<br>    Serial.println(httpRequestData);<br>    <br>    // You can comment the httpRequestData variable above<br>    // then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)<br>    //String httpRequestData = &quot;api_key=tPmAT5Ab3j7F9&amp;sensor=BME280&amp;location=Office&amp;value1=24.75&amp;value2=49.54&amp;value3=1005.14&quot;;<br><br>    // Send HTTP POST request<br>    int httpResponseCode = http.POST(httpRequestData);<br>     <br>    // If you need an HTTP request with a content type: text/plain<br>    //http.addHeader(&quot;Content-Type&quot;, &quot;text/plain&quot;);<br>    //int httpResponseCode = http.POST(&quot;Hello, World!&quot;);<br>    <br>    // If you need an HTTP request with a content type: application/json, use the following:<br>    //http.addHeader(&quot;Content-Type&quot;, &quot;application/json&quot;);<br>    //int httpResponseCode = http.POST(&quot;{\&quot;value1\&quot;:\&quot;19\&quot;,\&quot;value2\&quot;:\&quot;67\&quot;,\&quot;value3\&quot;:\&quot;78\&quot;}&quot;);<br>        <br>    if (httpResponseCode&gt;0) {<br>      Serial.print(&quot;HTTP Response code: &quot;);<br>      Serial.println(httpResponseCode);<br>    }<br>    else {<br>      Serial.print(&quot;Error code: &quot;);<br>      Serial.println(httpResponseCode);<br>    }<br>    // Free resources<br>    http.end();<br>  }<br>  else {<br>    Serial.println(&quot;WiFi Disconnected&quot;);<br>  }<br>  //Send an HTTP POST request every 30 seconds<br>  delay(30000);  <br>}</pre><p>You can see that it’s very time-sensitive, as how the data will be stored and shown to the webpage is based on time. Also as you can see on the loop() section, the procedure will make a HTTP POST request every 30 seconds (can be set) with the latest BME280 data. Make sure to connect the ESP32 and upload your codes!</p><h4>Result</h4><p>This is the result of the experiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*UTBhnMTKrRUuMwSe" /><figcaption>Serial Monitor</figcaption></figure><p>Open up your domain name to see the BME280 read data through your url, for example : <a href="http://example-domain.com/esp-data.php">http://example-domain.com/esp-data.php</a> .</p><p>The webpage should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*z5U5GvoZF_xovVtV.png" /><figcaption>Webpage Interface: Show Data Read by BME280</figcaption></figure><p>This will go on and on until you decided to take it down. This is a very next-level and interesting experiment because we have to utilize many devices and services. I hope I can really make one in the future, let’s really hope this pandemic can be settled down. Ciao bella (don’t forget to watch La Casa De Papel on Netflix).</p><blockquote>Make sure that this pandemic won’t prevent you into learning new things!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dd6a89caafd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saving Data Input from A Web (HTML) into SPIFFS (with Arduino IDE and ESP32)]]></title>
            <link>https://medium.com/@yonatanjori/saving-data-input-from-a-web-html-into-spiffs-with-arduino-ide-and-esp32-8b1351ed65ea?source=rss-543c6cda3bc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b1351ed65ea</guid>
            <dc:creator><![CDATA[Natan ]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 05:27:41 GMT</pubDate>
            <atom:updated>2020-04-26T06:08:09.612Z</atom:updated>
            <content:encoded><![CDATA[<p>Hel hel hel hello folks! So, getting rid of all the sensors that I used previously on my experiments, now I am going to try to explain how to create a web server to input some data in various data types then showing it in Arduino IDE’s serial monitor, by using a server that’ll be provided with the help of ESP32. By the way for this experiment, I ‘did’ this experiment with the help and documentation from my teammate, Jingga, so kudos to her.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*idu49y6VLeXDXaLT" /><figcaption>Form to SPIFFS</figcaption></figure><h4>Tools</h4><p>So, the tools that are needed for this experiment is very easy, you just basically need Arduino IDE and ESP32 (well and WiFi). But besides that we need ESPAsyncWebServer and AsyncTCP library installment on our Arduino IDE. And for the wiring configuration, you just have to plug the ESP32 to your computer/laptop, and done (but don’t forget to do all of the initial steps to make sure that your ESP32 can connect to the IDE, at this point of story, of course I’ve already handled this step).</p><h4>Code</h4><p>The HTML code for this experiment is quite simple, hence we code the html directly into our Arduino IDE code, as always, change the ssid and password variables according to the WiFi that’ll be used.</p><p>The variables or input form that we would like to input are inputSunSign, inputMoonSign, and inputRisingSign, and here is the code:</p><pre>#include &lt;Arduino.h&gt;<br>    #ifdef ESP32<br>    #include &lt;WiFi.h&gt;<br>    #include &lt;AsyncTCP.h&gt;<br>    /* #else<br>    #include &lt;ESP8266WiFi.h&gt;<br>    #include &lt;ESPAsyncTCP.h&gt; */<br>    #endif<br>    #include &lt;ESPAsyncWebServer.h&gt;</pre><pre>AsyncWebServer server(80);</pre><pre>// REPLACE WITH YOUR NETWORK CREDENTIALS<br>    const char* ssid = “anjingmaltese”;<br>    const char* password = “dinosaurus”;</pre><pre>const char* PARAM_INPUT_1 = “inputSunSign”;<br>    const char* PARAM_INPUT_2 = “inputMoonSign”;<br>    const char* PARAM_INPUT_3 = “inputRisingSign”;</pre><pre>// HTML web page to handle 3 input fields (inputSunSign, inputMoonSign, inputRisingSign)<br>    const char index_html[] PROGMEM = R”rawliteral(<br>    &lt;!DOCTYPE HTML&gt;&lt;html&gt;&lt;head&gt;<br>    &lt;title&gt;ESP Input Form&lt;/title&gt;<br>    &lt;meta name=”viewport” content=”width=device-width, initial-scale=1&quot;&gt;<br>    &lt;/head&gt;&lt;body&gt;<br>    &lt;form action=”/get”&gt;<br>    inputSunSign: &lt;input type=”text” name=”inputSunSign”&gt;<br>    &lt;input type=”submit” value=”Submit”&gt;<br>    &lt;/form&gt;&lt;br&gt;<br>    &lt;form action=”/get”&gt;<br>    inputMoonSign: &lt;input type=”text” name=”inputMoonSign”&gt;<br>    &lt;input type=”submit” value=”Submit”&gt;<br>    &lt;/form&gt;&lt;br&gt;<br>    &lt;form action=”/get”&gt;<br>    inputRisingSign: &lt;input type=”text” name=”inputRisingSign”&gt;<br>    &lt;input type=”submit” value=”Submit”&gt;<br>    &lt;/form&gt;<br>    &lt;/body&gt;&lt;/html&gt;)rawliteral”;</pre><pre>void notFound(AsyncWebServerRequest *request) {<br>    request-&gt;send(404, “text/plain”, “Not found”);<br>    }</pre><pre>void setup() {<br>    Serial.begin(115200);<br>    WiFi.mode(WIFI_STA);<br>    WiFi.begin(ssid, password);<br>    if (WiFi.waitForConnectResult() != WL_CONNECTED) {<br>    Serial.println(“WiFi Failed!”);<br>    return;<br>    }<br>    Serial.println();<br>    Serial.print(“IP Address: “);<br>    Serial.println(WiFi.localIP());</pre><pre>// Send web page with input fields to client<br>    server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request){<br>    request-&gt;send_P(200, “text/html”, index_html);<br>    });</pre><pre>// Send a GET request to &lt;ESP_IP&gt;/get?inputSunSign=&lt;inputMessage&gt;<br>    server.on(“/get”, HTTP_GET, [] (AsyncWebServerRequest *request) {<br>    String inputMessage;<br>    String inputParam;<br>    // GET inputSunSign value on &lt;ESP_IP&gt;/get?inputSunSign=&lt;inputMessage&gt;<br>    if (request-&gt;hasParam(PARAM_INPUT_1)) {<br>    inputMessage = request-&gt;getParam(PARAM_INPUT_1)-&gt;value();<br>    inputParam = PARAM_INPUT_1;<br>    }<br>    // GET inputMoonSign value on &lt;ESP_IP&gt;/get?inputMoonSign=&lt;inputMessage&gt;<br>    else if (request-&gt;hasParam(PARAM_INPUT_2)) {<br>    inputMessage = request-&gt;getParam(PARAM_INPUT_2)-&gt;value();<br>    inputParam = PARAM_INPUT_2;<br>    }<br>    // GET inputRisingSign value on &lt;ESP_IP&gt;/get?inputRisingSign=&lt;inputMessage&gt;<br>    else if (request-&gt;hasParam(PARAM_INPUT_3)) {<br>    inputMessage = request-&gt;getParam(PARAM_INPUT_3)-&gt;value();<br>    inputParam = PARAM_INPUT_3;<br>    }<br>    else {<br>    inputMessage = “No message sent”;<br>    inputParam = “none”;<br>    }<br>    Serial.println(inputMessage);<br>    request-&gt;send(200, “text/html”, “HTTP GET request sent to your ESP on input field (“<br>    + inputParam + “) with value: “ + inputMessage +<br>    “&lt;br&gt;&lt;a href=\”/\”&gt;Return to Home Page&lt;/a&gt;”);<br>    });<br>    server.onNotFound(notFound);<br>    server.begin();<br>    }</pre><pre>void loop() {</pre><pre>}</pre><p>As you can see the loop() is empty because this is a asynchronous server and the server basically will always run after the command server.begin().</p><p>After doing so, compile and upload the code then set BAUD rate at 115200 then see your serial monitor, you’ll get the IP address of the server that is going to be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*QuZrvm-GAmFkZZyv.png" /><figcaption>Server IP Address</figcaption></figure><p>Then, go to the IP address, you will see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*o0yjsN_h4nwVE2jx.png" /><figcaption>Server Interface (HTML)</figcaption></figure><p>As you can see, the label or the ‘form’ is set according to our willing which are inputSunSign, inputMoonSign, inputRisingSign, these has previously coded in the code above. After that, try to fill in the form and click submit, it’ll show you something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*tzeTGVSSZBxgSBIi.png" /><figcaption>Successful Submit New Page</figcaption></figure><p>After that, we will get into how to saving the input field/form to SPIFFS.</p><h4>SPIFFS</h4><p>Serial Peripheral Interface Flash File System is a light-weight file system for microcontrollers with an SPI flash chips such as ESP32. To save the input from a form on a web server into SPIFFS, here is the code, notice how we add the SPIFFS library, also don’t forget to set the ssid and password accordingly:</p><pre>#include &lt;Arduino.h&gt;</pre><pre>#include &lt;WiFi.h&gt;<br>    #include &lt;AsyncTCP.h&gt;<br>    #include &lt;SPIFFS.h&gt;<br>    /* #else<br>    #include &lt;ESP8266WiFi.h&gt;<br>    #include &lt;ESPAsyncTCP.h&gt;<br>    #include &lt;Hash.h&gt;<br>    #include &lt;FS.h&gt;<br>    #endif */<br>    #include &lt;ESPAsyncWebServer.h&gt;</pre><pre>AsyncWebServer server(80);</pre><pre>// REPLACE WITH YOUR NETWORK CREDENTIALS<br>    const char* ssid = “plis”;<br>    const char* password = “87654321”;</pre><pre>const char* PARAM_STRING = “inputSunSign”;<br>    const char* PARAM_INT = “inputHouse”;<br>    const char* PARAM_FLOAT = “inputAscensiorect”;</pre><pre>// HTML web page to handle 3 input fields (inputSunSign, inputHouse, inputAscensiorect)<br>    const char index_html[] PROGMEM = R”rawliteral(<br>    &lt;!DOCTYPE HTML&gt;&lt;html&gt;&lt;head&gt;<br>    &lt;title&gt;ESP Input Form&lt;/title&gt;<br>    &lt;meta name=”viewport” content=”width=device-width, initial-scale=1&quot;&gt;<br>    &lt;script&gt;<br>    function submitMessage() {<br>    alert(“Saved value to ESP SPIFFS”);<br>    setTimeout(function(){ document.location.reload(false); }, 500);<br>    }<br>    &lt;/script&gt;&lt;/head&gt;&lt;body&gt;<br>    &lt;form action=”/get” target=”hidden-form”&gt;<br>    inputSunSign (current value %inputSunSign%): &lt;input type=”text” name=”inputSunSign”&gt;<br>    &lt;input type=”submit” value=”Submit” onclick=”submitMessage()”&gt;<br>    &lt;/form&gt;&lt;br&gt;<br>    &lt;form action=”/get” target=”hidden-form”&gt;<br>    inputHouse (current value %inputHouse%): &lt;input type=”number “ name=”inputHouse”&gt;<br>    &lt;input type=”submit” value=”Submit” onclick=”submitMessage()”&gt;<br>    &lt;/form&gt;&lt;br&gt;<br>    &lt;form action=”/get” target=”hidden-form”&gt;<br>    inputAscensiorect (current value %inputAscensiorect%): &lt;input type=”number “ name=”inputAscensiorect”&gt;<br>    &lt;input type=”submit” value=”Submit” onclick=”submitMessage()”&gt;<br>    &lt;/form&gt;<br>    &lt;iframe style=”display:none” name=”hidden-form”&gt;&lt;/iframe&gt;<br>    &lt;/body&gt;&lt;/html&gt;)rawliteral”;</pre><pre>void notFound(AsyncWebServerRequest *request) {<br>    request-&gt;send(404, “text/plain”, “Not found”);<br>    }</pre><pre>String readFile(fs::FS &amp;fs, const char * path){<br>    Serial.printf(“Reading file: %s\r\n”, path);<br>    File file = fs.open(path, “r”);<br>    if(!file || file.isDirectory()){<br>    Serial.println(“- empty file or failed to open file”);<br>    return String();<br>    }<br>    Serial.println(“- read from file:”);<br>    String fileContent;<br>    while(file.available()){<br>    fileContent+=String((char)file.read());<br>    }<br>    Serial.println(fileContent);<br>    return fileContent;<br>    }</pre><pre>void writeFile(fs::FS &amp;fs, const char * path, const char * message){<br>    Serial.printf(“Writing file: %s\r\n”, path);<br>    File file = fs.open(path, “w”);<br>    if(!file){<br>    Serial.println(“- failed to open file for writing”);<br>    return;<br>    }<br>    if(file.print(message)){<br>    Serial.println(“- file written”);<br>    } else {<br>    Serial.println(“- write failed”);<br>    }<br>    }</pre><pre>// Replaces placeholder with stored values<br>    String processor(const String&amp; var){<br>    //Serial.println(var);<br>    if(var == “inputSunSign”){<br>    return readFile(SPIFFS, “/inputSunSign.txt”);<br>    }<br>    else if(var == “inputHouse”){<br>    return readFile(SPIFFS, “/inputHouse.txt”);<br>    }<br>    else if(var == “inputAscensiorect”){<br>    return readFile(SPIFFS, “/inputAscensiorect.txt”);<br>    }<br>    return String();<br>    }</pre><pre>void setup() {<br>    Serial.begin(115200);<br>    // Initialize SPIFFS<br>    #ifdef ESP32<br>    if(!SPIFFS.begin(true)){<br>    Serial.println(“An Error has occurred while mounting SPIFFS”);<br>    return;<br>    }<br>    #else<br>    if(!SPIFFS.begin()){<br>    Serial.println(“An Error has occurred while mounting SPIFFS”);<br>    return;<br>    }<br>    #endif</pre><pre>WiFi.mode(WIFI_STA);<br>    WiFi.begin(ssid, password);<br>    if (WiFi.waitForConnectResult() != WL_CONNECTED) {<br>    Serial.println(“WiFi Failed!”);<br>    return;<br>    }<br>    Serial.println();<br>    Serial.print(“IP Address: “);<br>    Serial.println(WiFi.localIP());</pre><pre>// Send web page with input fields to client<br>    server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request){<br>    request-&gt;send_P(200, “text/html”, index_html, processor);<br>    });</pre><pre>// Send a GET request to &lt;ESP_IP&gt;/get?inputSunSign=&lt;inputMessage&gt;<br>    server.on(“/get”, HTTP_GET, [] (AsyncWebServerRequest *request) {<br>    String inputMessage;<br>    // GET inputSunSign value on &lt;ESP_IP&gt;/get?inputSunSign=&lt;inputMessage&gt;<br>    if (request-&gt;hasParam(PARAM_STRING)) {<br>    inputMessage = request-&gt;getParam(PARAM_STRING)-&gt;value();<br>    writeFile(SPIFFS, “/inputSunSign.txt”, inputMessage.c_str());<br>    }<br>    // GET inputHouse value on &lt;ESP_IP&gt;/get?inputHouse=&lt;inputMessage&gt;<br>    else if (request-&gt;hasParam(PARAM_INT)) {<br>    inputMessage = request-&gt;getParam(PARAM_INT)-&gt;value();<br>    writeFile(SPIFFS, “/inputHouse.txt”, inputMessage.c_str());<br>    }<br>    // GET inputAscensiorect value on &lt;ESP_IP&gt;/get?inputAscensiorect=&lt;inputMessage&gt;<br>    else if (request-&gt;hasParam(PARAM_FLOAT)) {<br>    inputMessage = request-&gt;getParam(PARAM_FLOAT)-&gt;value();<br>    writeFile(SPIFFS, “/inputAscensiorect.txt”, inputMessage.c_str());<br>    }<br>    else {<br>    inputMessage = “No message sent”;<br>    }<br>    Serial.println(inputMessage);<br>    request-&gt;send(200, “text/text”, inputMessage);<br>    });<br>    server.onNotFound(notFound);<br>    server.begin();<br>    }</pre><pre>void loop() {<br>    // To access your stored values on inputSunSign, inputHouse, inputAscensiorect<br>    String yourinputSunSign = readFile(SPIFFS, “/inputSunSign.txt”);<br>    Serial.print(“*** Your inputSunSign: “);<br>    Serial.println(yourinputSunSign);</pre><pre>int yourinputHouse = readFile(SPIFFS, “/inputHouse.txt”).toInt();<br>    Serial.print(“*** Your inputHouse: “);<br>    Serial.println(yourinputHouse);</pre><pre>float yourinputAscensiorect = readFile(SPIFFS, “/inputAscensiorect.txt”).toFloat();<br>    Serial.print(“*** Your inputAscensiorect: “);<br>    Serial.println(yourinputAscensiorect);<br>    delay(5000);<br>    }</pre><p>After uploading the code, open the serial monitor again to get the server’s IP address then open the said IP address. It’ll show some interface like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*F0pglUz5m-TQED3e.png" /><figcaption>Server HTML Interface</figcaption></figure><p>If you were to submit a value, you’ll get a pop-up notifications such as this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*4qUDB8QOR5SkuFL8.png" /><figcaption>Notifications Succeed Submit</figcaption></figure><p>After submitting a new value, the current value of a label will be changed according to your last submit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*OFFfy0coO-9Emt03.png" /><figcaption>Updated Current Value</figcaption></figure><p>Meanwhile, on the serial monitor on Arduino IDE, you will get a little something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*O33IQrEWgugipAS2.png" /><figcaption>Input Value Shown on Serial Monitor</figcaption></figure><p>See, how you can see the value inputted previously on the server, that means that the experiment is successful.</p><p>So that basically that, this feature on ESP32 is very nice where you can gain information from an inputted data on a server, and this can be obviously used in future development such as gaining info/feedback/etc from a client and other stuff. <br>So there you have it another experiment by me and my team! See you on the next one peeps!</p><p>Remember:</p><blockquote>Make sure that this pandemic won’t prevent you into learning new things!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b1351ed65ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Logging]]></title>
            <link>https://medium.com/@yonatanjori/data-logging-f6c83c39b6c?source=rss-543c6cda3bc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6c83c39b6c</guid>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[record]]></category>
            <category><![CDATA[datalogging]]></category>
            <category><![CDATA[sheet]]></category>
            <category><![CDATA[bme280]]></category>
            <dc:creator><![CDATA[Natan ]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 04:30:57 GMT</pubDate>
            <atom:updated>2020-04-26T04:31:48.275Z</atom:updated>
            <content:encoded><![CDATA[<h3>BME280 Data Logging on Google Sheet (With ESP32 and IFTTT Use)</h3><p>So, continuing my previous story, what if I want the raw data, and not just the graph, what if I want the read data on BME280 to be saved on a database such as google sheet. Hm this is a very exciting project, because if this works out, the saved data can be used for further knowledge and future development such as weather predictions and other stuff. This project will be very useful and insightful for lots of reason besides some that I’ve write before, the provided data can be used for more attractive visualization and probability, and can be useful for certain parties eg government on how they should act. such as watering the forest if there’ll be a drought there, etc.</p><p>So yes, on this project, the read data will be saved on Google Sheet using a third party service called If This Then That (IFTTT) every 30 minutes (you can configure this later on). So the cycle basically goes like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*WVeyXMEaYBq0zR39" /><figcaption>Data Read and Saving Cycle</figcaption></figure><p>So first thing is basic just as we do on several previous experiment, which is connecting the ESP32 to a WiFi and data reading by BME280. After that, the ESP32 will communicate with the IFTTT Webhooks service that’ll publish the BME280 readings to a spreadsheet (Google) that is saved in your Google Drive’s folder. After that, the ESP will go into a sleep mode for 30 minutes (editable later on), then will wake up after that 30 minutes sleep. After waking up, the ESP32 will connect to a set WiFi, and this cycle goes on and on.</p><h4>Tools</h4><p>So the needed tools is very simple:</p><ol><li>ESP32</li><li>BME280</li><li>Breadboard</li><li>Jumper cables</li><li>Arduino IDE</li><li>Google Account (for sheet and drive)</li></ol><p>And besides that here are some needed libraries on Arduino IDE that have to installed:</p><ol><li>Adafruit Library (BME280 and Unified Sensor)</li></ol><p>See, it is that easy.</p><p>So after gathering the tools and installment, here is the configuration of the tools:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*gXHwMTZTcGf1DL5p" /><figcaption>Wiring Configration</figcaption></figure><p>The wiring is basically the same as previous experiment, as we’re just changing on how the data will be saved.</p><h4>Code</h4><p>IFTTT (If This Then That):</p><p>Has the ability to connect apps, devices, services from different developers in order to trigger one or more automations involving said apps, devices, and services. The ‘this’ is a trigger from an app/service that will call for a ‘that’ from the same or another app/service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*9kyUUSyH47yY2FHY.png" /><figcaption>IFTTT</figcaption></figure><p>Steps in order to do this experiment:</p><ol><li>Visit ifttt.com and enter your account mail</li><li>Create new applet and choose Webhooks service by clicking +this button</li><li>Choose a trigger: receive a web request, name it as ‘bme280_readings’ for example</li><li>click on +that button and choose Google Sheet as the action service, choose add a row to spreadsheet. Give the spreadsheet a name and directory on Drive and leave the formatted row as default</li><li>Finish!</li><li>For testing: go to Webhooks service page &gt; Documentation</li><li>The page will display a unique API key, fill the fields with example shown below and hit “Test it” button. Then, go to your Google Drive &gt; IFTTT and check if there is any new spreadsheet with the data that you just triggered. Then you’re ready to go</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*NnfgAnZRHhxNqtiF" /><figcaption>Testing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*BmIC8uxuvKqozR0i" /><figcaption>Testing Yield</figcaption></figure><p>Code:</p><p>Change the ssid and password variables corresponding to your WiFi credentials, also you can set the timer of sleep (explained before) on TIME_TO_SLEEP variable.</p><pre>#ifdef ESP32<br>  #include &lt;WiFi.h&gt;<br>#else<br>  #include &lt;ESP8266WiFi.h&gt;<br>#endif<br><br>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_Sensor.h&gt;<br>#include &lt;Adafruit_BME280.h&gt;<br><br>// Replace with your SSID and Password<br>const char* ssid     = &quot;REPLACE_WITH_YOUR_SSID&quot;;<br>const char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;<br><br>// Replace with your unique IFTTT URL resource<br>const char* resource = &quot;REPLACE_WITH_YOUR_IFTTT_URL_RESOURCE&quot;;<br><br>// How your resource variable should look like, but with your own API KEY (that API KEY below is just an example):<br>//const char* resource = &quot;/trigger/bme280_readings/with/key/nAZjOphL3d-ZO4N3k64-1A7gTlNSrxMJdmqy3&quot;;<br><br>// Maker Webhooks IFTTT<br>const char* server = &quot;maker.ifttt.com&quot;;<br><br>// Time to sleep<br>uint64_t uS_TO_S_FACTOR = 1000000;  // Conversion factor for micro seconds to seconds<br>// sleep for 30 minutes = 1800 seconds<br>uint64_t TIME_TO_SLEEP = 1800;<br><br>// Uncomment to use BME280 SPI<br>/*#include &lt;SPI.h&gt;<br>#define BME_SCK 13<br>#define BME_MISO 12<br>#define BME_MOSI 11<br>#define BME_CS 10*/<br><br>#define SEALEVELPRESSURE_HPA (1013.25)<br><br>Adafruit_BME280 bme; // I2C<br>//Adafruit_BME280 bme(BME_CS); // hardware SPI<br>//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI<br><br>void setup() {<br>  Serial.begin(115200); <br>  delay(2000);<br><br>  // initialize BME280 sensor<br>  bool status;<br>  status = bme.begin(0x76);  <br>  if (!status) {<br>    Serial.println(&quot;Could not find a valid BME280 sensor, check wiring!&quot;);<br>    while (1);<br>  }<br><br>  initWifi();<br>  makeIFTTTRequest();<br>    <br>  #ifdef ESP32<br>    // enable timer deep sleep<br>    esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);    <br>    Serial.println(&quot;Going to sleep now&quot;);<br>    // start deep sleep for 3600 seconds (60 minutes)<br>    esp_deep_sleep_start();<br>  #else<br>    // Deep sleep mode for 3600 seconds (60 minutes)<br>    Serial.println(&quot;Going to sleep now&quot;);<br>    ESP.deepSleep(TIME_TO_SLEEP * uS_TO_S_FACTOR); <br>  #endif<br>}<br><br>void loop() {<br>  // sleeping so wont get here <br>}<br><br>// Establish a Wi-Fi connection with your router<br>void initWifi() {<br>  Serial.print(&quot;Connecting to: &quot;); <br>  Serial.print(ssid);<br>  WiFi.begin(ssid, password);  <br><br>  int timeout = 10 * 4; // 10 seconds<br>  while(WiFi.status() != WL_CONNECTED  &amp;&amp; (timeout-- &gt; 0)) {<br>    delay(250);<br>    Serial.print(&quot;.&quot;);<br>  }<br>  Serial.println(&quot;&quot;);<br><br>  if(WiFi.status() != WL_CONNECTED) {<br>     Serial.println(&quot;Failed to connect, going back to sleep&quot;);<br>  }<br><br>  Serial.print(&quot;WiFi connected in: &quot;); <br>  Serial.print(millis());<br>  Serial.print(&quot;, IP address: &quot;); <br>  Serial.println(WiFi.localIP());<br>}<br><br>// Make an HTTP request to the IFTTT web service<br>void makeIFTTTRequest() {<br>  Serial.print(&quot;Connecting to &quot;); <br>  Serial.print(server);<br>  <br>  WiFiClient client;<br>  int retries = 5;<br>  while(!!!client.connect(server, 80) &amp;&amp; (retries-- &gt; 0)) {<br>    Serial.print(&quot;.&quot;);<br>  }<br>  Serial.println();<br>  if(!!!client.connected()) {<br>    Serial.println(&quot;Failed to connect...&quot;);<br>  }<br>  <br>  Serial.print(&quot;Request resource: &quot;); <br>  Serial.println(resource);<br><br>  // Temperature in Celsius<br>  String jsonObject = String(&quot;{\&quot;value1\&quot;:\&quot;&quot;) + bme.readTemperature() + &quot;\&quot;,\&quot;value2\&quot;:\&quot;&quot; + (bme.readPressure()/100.0F)<br>                      + &quot;\&quot;,\&quot;value3\&quot;:\&quot;&quot; + bme.readHumidity() + &quot;\&quot;}&quot;;<br>                      <br>  // Comment the previous line and uncomment the next line to publish temperature readings in Fahrenheit                    <br>  /*String jsonObject = String(&quot;{\&quot;value1\&quot;:\&quot;&quot;) + (1.8 * bme.readTemperature() + 32) + &quot;\&quot;,\&quot;value2\&quot;:\&quot;&quot; <br>                      + (bme.readPressure()/100.0F) + &quot;\&quot;,\&quot;value3\&quot;:\&quot;&quot; + bme.readHumidity() + &quot;\&quot;}&quot;;*/<br>                      <br>  client.println(String(&quot;POST &quot;) + resource + &quot; HTTP/1.1&quot;);<br>  client.println(String(&quot;Host: &quot;) + server); <br>  client.println(&quot;Connection: close\r\nContent-Type: application/json&quot;);<br>  client.print(&quot;Content-Length: &quot;);<br>  client.println(jsonObject.length());<br>  client.println();<br>  client.println(jsonObject);<br>        <br>  int timeout = 5 * 10; // 5 seconds             <br>  while(!!!client.available() &amp;&amp; (timeout-- &gt; 0)){<br>    delay(100);<br>  }<br>  if(!!!client.available()) {<br>    Serial.println(&quot;No response...&quot;);<br>  }<br>  while(client.available()){<br>    Serial.write(client.read());<br>  }<br>  <br>  Serial.println(&quot;\nclosing connection&quot;);<br>  client.stop(); <br>}</pre><h4>Result</h4><p>After all that, upload the code and don’t forget to connect to a chosen and set WiFi (for IDE config). But after that, you can test your experiment, and here is an example of the sheet’s record:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*OSc_mIQIBRS1RvCT" /><figcaption>Experiment’s Yield</figcaption></figure><p>So you do those then you’ll get that! Aha! I hope I can really try the real experiment, as of now I don’t have the needed tools, and I hope you can too! Ciao…</p><blockquote>Make sure that this pandemic won’t prevent you into learning new things!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6c83c39b6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real Time Weather Data-Visualization using BME280 and ESP32]]></title>
            <link>https://medium.com/@yonatanjori/real-time-weather-data-visualization-using-bme280-and-esp32-bb93946938fc?source=rss-543c6cda3bc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb93946938fc</guid>
            <category><![CDATA[weather]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[bme]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[bme280]]></category>
            <dc:creator><![CDATA[Natan ]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 02:31:05 GMT</pubDate>
            <atom:updated>2020-04-26T02:31:05.725Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello folks! Back at it again with me, I know it’s been a while since I write in here, but well oh well, during this pandemic I got really interested in data visualization on ESP32 using BME280.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MQ-ns7eBvSfv4xOq.jpg" /><figcaption>Weather Data Visualization using BME280 and ESP32</figcaption></figure><p>But, the problem is that I didn’t bring any of my ESP32 kit to my hometown, since I went home because this pandemic. Usually while we’re going to do an experiment, we’d gather and do this and that on making sure our experiment works, but during this pandemic, because we’re separated and doesn’t have the kit needed by ourselves, we’re just going to learn about how exactly does this experiment work.</p><h4>Tools</h4><p>So, continuing my past experiment (supposedly), which is showing the read data by BME280 using a web server, now instead of just the numbers, we want to show you how to show the numbers, but in graph. So the needed tools are:</p><ol><li>ESP32</li><li>BME280</li><li>Breadboard</li><li>Jumper cables</li><li>Arduino IDE</li></ol><p>Before getting right into the code and implementation itself, there are several plugins and libraries that I had to install on my Arduino IDE, and they are:</p><ol><li>AsyncTCP</li><li>Adafruit Sensor Library (BME280 and Unified Sensor)</li><li>ESPAsyncWebServer</li><li>FileSystem Uploader Plugin</li></ol><p>After doing that, the next thing that I had to do is configuring the wiring or electrical parts. Here is a pic of one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*XSMuDS-mPLHyjCwx" /><figcaption>Wiring Configuration</figcaption></figure><h4>Code</h4><p>So, right into the code itself. As we all know the graph will be shown on a web server. Hence, in order to do that, we have to have an html code on how we want the web server to look like. And here is one:</p><pre>&lt;!DOCTYPE HTML&gt;&lt;html&gt;<br>&lt;!-- Rui Santos - Complete project details at https://RandomNerdTutorials.com<br><br>Permission is hereby granted, free of charge, to any person obtaining a copy<br>of this software and associated documentation files.<br>The above copyright notice and this permission notice shall be included in all<br>copies or substantial portions of the Software. --&gt;<br>&lt;head&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>  &lt;script src=&quot;https://code.highcharts.com/highcharts.js&quot;&gt;&lt;/script&gt;<br>  &lt;style&gt;<br>    body {<br>      min-width: 310px;<br>    	max-width: 800px;<br>    	height: 400px;<br>      margin: 0 auto;<br>    }<br>    h2 {<br>      font-family: Arial;<br>      font-size: 2.5rem;<br>      text-align: center;<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h2&gt;ESP Weather Station&lt;/h2&gt;<br>  &lt;div id=&quot;chart-temperature&quot; class=&quot;container&quot;&gt;&lt;/div&gt;<br>  &lt;div id=&quot;chart-humidity&quot; class=&quot;container&quot;&gt;&lt;/div&gt;<br>  &lt;div id=&quot;chart-pressure&quot; class=&quot;container&quot;&gt;&lt;/div&gt;<br>&lt;/body&gt;<br>&lt;script&gt;<br>var chartT = new Highcharts.Chart({<br>  chart:{ renderTo : &#39;chart-temperature&#39; },<br>  title: { text: &#39;BME280 Temperature&#39; },<br>  series: [{<br>    showInLegend: false,<br>    data: []<br>  }],<br>  plotOptions: {<br>    line: { animation: false,<br>      dataLabels: { enabled: true }<br>    },<br>    series: { color: &#39;#059e8a&#39; }<br>  },<br>  xAxis: { type: &#39;datetime&#39;,<br>    dateTimeLabelFormats: { second: &#39;%H:%M:%S&#39; }<br>  },<br>  yAxis: {<br>    title: { text: &#39;Temperature (Celsius)&#39; }<br>    //title: { text: &#39;Temperature (Fahrenheit)&#39; }<br>  },<br>  credits: { enabled: false }<br>});<br>setInterval(function ( ) {<br>  var xhttp = new XMLHttpRequest();<br>  xhttp.onreadystatechange = function() {<br>    if (this.readyState == 4 &amp;&amp; this.status == 200) {<br>      var x = (new Date()).getTime(),<br>          y = parseFloat(this.responseText);<br>      //console.log(this.responseText);<br>      if(chartT.series[0].data.length &gt; 40) {<br>        chartT.series[0].addPoint([x, y], true, true, true);<br>      } else {<br>        chartT.series[0].addPoint([x, y], true, false, true);<br>      }<br>    }<br>  };<br>  xhttp.open(&quot;GET&quot;, &quot;/temperature&quot;, true);<br>  xhttp.send();<br>}, 30000 ) ;<br><br>var chartH = new Highcharts.Chart({<br>  chart:{ renderTo:&#39;chart-humidity&#39; },<br>  title: { text: &#39;BME280 Humidity&#39; },<br>  series: [{<br>    showInLegend: false,<br>    data: []<br>  }],<br>  plotOptions: {<br>    line: { animation: false,<br>      dataLabels: { enabled: true }<br>    }<br>  },<br>  xAxis: {<br>    type: &#39;datetime&#39;,<br>    dateTimeLabelFormats: { second: &#39;%H:%M:%S&#39; }<br>  },<br>  yAxis: {<br>    title: { text: &#39;Humidity (%)&#39; }<br>  },<br>  credits: { enabled: false }<br>});<br>setInterval(function ( ) {<br>  var xhttp = new XMLHttpRequest();<br>  xhttp.onreadystatechange = function() {<br>    if (this.readyState == 4 &amp;&amp; this.status == 200) {<br>      var x = (new Date()).getTime(),<br>          y = parseFloat(this.responseText);<br>      //console.log(this.responseText);<br>      if(chartH.series[0].data.length &gt; 40) {<br>        chartH.series[0].addPoint([x, y], true, true, true);<br>      } else {<br>        chartH.series[0].addPoint([x, y], true, false, true);<br>      }<br>    }<br>  };<br>  xhttp.open(&quot;GET&quot;, &quot;/humidity&quot;, true);<br>  xhttp.send();<br>}, 30000 ) ;<br><br>var chartP = new Highcharts.Chart({<br>  chart:{ renderTo:&#39;chart-pressure&#39; },<br>  title: { text: &#39;BME280 Pressure&#39; },<br>  series: [{<br>    showInLegend: false,<br>    data: []<br>  }],<br>  plotOptions: {<br>    line: { animation: false,<br>      dataLabels: { enabled: true }<br>    },<br>    series: { color: &#39;#18009c&#39; }<br>  },<br>  xAxis: {<br>    type: &#39;datetime&#39;,<br>    dateTimeLabelFormats: { second: &#39;%H:%M:%S&#39; }<br>  },<br>  yAxis: {<br>    title: { text: &#39;Pressure (hPa)&#39; }<br>  },<br>  credits: { enabled: false }<br>});<br>setInterval(function ( ) {<br>  var xhttp = new XMLHttpRequest();<br>  xhttp.onreadystatechange = function() {<br>    if (this.readyState == 4 &amp;&amp; this.status == 200) {<br>      var x = (new Date()).getTime(),<br>          y = parseFloat(this.responseText);<br>      //console.log(this.responseText);<br>      if(chartP.series[0].data.length &gt; 40) {<br>        chartP.series[0].addPoint([x, y], true, true, true);<br>      } else {<br>        chartP.series[0].addPoint([x, y], true, false, true);<br>      }<br>    }<br>  };<br>  xhttp.open(&quot;GET&quot;, &quot;/pressure&quot;, true);<br>  xhttp.send();<br>}, 30000 ) ;<br>&lt;/script&gt;<br>&lt;/html&gt;</pre><p>As you can see on the code, it has lots of determination with time, hence the graph. Also on how they’re going to show temperature, humidity, and pressure based on a “data”, that of course will be provided later on with Arduino IDE configuration and the ESP32 itself.</p><p>So after the html code, the next thing that I had to do is configuring the Arduino IDE code, in making sure that the data that is read by BME280 would be read and transferred nicely into the web server. Here is one but do not forget on changing the ssid and password variables according to yous:</p><pre>#ifdef ESP32<br>  #include &lt;WiFi.h&gt;<br>  #include &lt;ESPAsyncWebServer.h&gt;<br>  #include &lt;SPIFFS.h&gt;<br>#else<br>  #include &lt;Arduino.h&gt;<br>  #include &lt;ESP8266WiFi.h&gt;<br>  #include &lt;Hash.h&gt;<br>  #include &lt;ESPAsyncTCP.h&gt;<br>  #include &lt;ESPAsyncWebServer.h&gt;<br>  #include &lt;FS.h&gt;<br>#endif<br>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_Sensor.h&gt;<br>#include &lt;Adafruit_BME280.h&gt;<br><br>/*#include &lt;SPI.h&gt;<br>#define BME_SCK 18<br>#define BME_MISO 19<br>#define BME_MOSI 23<br>#define BME_CS 5*/<br><br>Adafruit_BME280 bme; // I2C<br>//Adafruit_BME280 bme(BME_CS); // hardware SPI<br>//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI<br><br>// Replace with your network credentials<br>const char* ssid = &quot;REPLACE_WITH_YOUR_SSID&quot;;<br>const char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;<br><br>// Create AsyncWebServer object on port 80<br>AsyncWebServer server(80);<br><br>String readBME280Temperature() {<br>  // Read temperature as Celsius (the default)<br>  float t = bme.readTemperature();<br>  // Convert temperature to Fahrenheit<br>  //t = 1.8 * t + 32;<br>  if (isnan(t)) {    <br>    Serial.println(&quot;Failed to read from BME280 sensor!&quot;);<br>    return &quot;&quot;;<br>  }<br>  else {<br>    Serial.println(t);<br>    return String(t);<br>  }<br>}<br><br>String readBME280Humidity() {<br>  float h = bme.readHumidity();<br>  if (isnan(h)) {<br>    Serial.println(&quot;Failed to read from BME280 sensor!&quot;);<br>    return &quot;&quot;;<br>  }<br>  else {<br>    Serial.println(h);<br>    return String(h);<br>  }<br>}<br><br>String readBME280Pressure() {<br>  float p = bme.readPressure() / 100.0F;<br>  if (isnan(p)) {<br>    Serial.println(&quot;Failed to read from BME280 sensor!&quot;);<br>    return &quot;&quot;;<br>  }<br>  else {<br>    Serial.println(p);<br>    return String(p);<br>  }<br>}<br><br>void setup(){<br>  // Serial port for debugging purposes<br>  Serial.begin(115200);<br>  <br>  bool status; <br>  // default settings<br>  // (you can also pass in a Wire library object like &amp;Wire2)<br>  status = bme.begin(0x76);  <br>  if (!status) {<br>    Serial.println(&quot;Could not find a valid BME280 sensor, check wiring!&quot;);<br>    while (1);<br>  }<br><br>  // Initialize SPIFFS<br>  if(!SPIFFS.begin()){<br>    Serial.println(&quot;An Error has occurred while mounting SPIFFS&quot;);<br>    return;<br>  }<br><br>  // Connect to Wi-Fi<br>  WiFi.begin(ssid, password);<br>  while (WiFi.status() != WL_CONNECTED) {<br>    delay(1000);<br>    Serial.println(&quot;Connecting to WiFi..&quot;);<br>  }<br><br>  // Print ESP32 Local IP Address<br>  Serial.println(WiFi.localIP());<br><br>  // Route for root / web page<br>  server.on(&quot;/&quot;, HTTP_GET, [](AsyncWebServerRequest *request){<br>    request-&gt;send(SPIFFS, &quot;/index.html&quot;);<br>  });<br>  server.on(&quot;/temperature&quot;, HTTP_GET, [](AsyncWebServerRequest *request){<br>    request-&gt;send_P(200, &quot;text/plain&quot;, readBME280Temperature().c_str());<br>  });<br>  server.on(&quot;/humidity&quot;, HTTP_GET, [](AsyncWebServerRequest *request){<br>    request-&gt;send_P(200, &quot;text/plain&quot;, readBME280Humidity().c_str());<br>  });<br>  server.on(&quot;/pressure&quot;, HTTP_GET, [](AsyncWebServerRequest *request){<br>    request-&gt;send_P(200, &quot;text/plain&quot;, readBME280Pressure().c_str());<br>  });<br><br>  // Start server<br>  server.begin();<br>}<br> <br>void loop(){<br>  <br>}</pre><p>As you can see on the code, the void loop is empty. This is because we’re trying to build an asynchronous web server, hence we don’t need to write anything on the loop(). Meanwhile on the setup(), we call the functions that return the sensor reading according to the read data on BME280, and also on the last segment of setup(), the server finally begun.</p><h4>Result</h4><p>Go to Tools &gt; ESP32 Sketch Data Upload on Arduino IDE, open serial monitor and set the BAUD rate on 115200. The upload and try the code. Before that, make sure your laptop is connected to the WiFi that’ll be used by the ESP32 itself. Firstly, you’re going to be given an IP address on the serial monitor, that is the server that’ll show the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*BSuppg6haKSSwAdk" /><figcaption>Server IP Address</figcaption></figure><p>After doing so, open the said IP address through your internet explorer. Then this kind of graph will be shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/0*4EMTNt-TUuMH-7c9" /><figcaption>The Asynchronous Server (Graph)</figcaption></figure><p>So that was my learning on how to create a real-time weather data visualization using BME280 and ESP32. Of course I really wanted to try this by myself, but until this pandemic settle down, I won’t be, because I don’t have the needed tools and the bravery to buy it myself. Stay healthy peeps, don’t forget to wash your hands.</p><blockquote>Make sure that this pandemic won’t prevent you into learning new things!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb93946938fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supposedly: Do An Experiment on Weather Station using ESP32 and BME280]]></title>
            <link>https://medium.com/@yonatanjori/supposedly-do-an-experiment-on-weather-station-using-esp32-and-bme280-3753310e3478?source=rss-543c6cda3bc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3753310e3478</guid>
            <dc:creator><![CDATA[Natan ]]></dc:creator>
            <pubDate>Sun, 29 Mar 2020 18:39:21 GMT</pubDate>
            <atom:updated>2020-03-30T03:57:37.672Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello guys, so connecting to my previous story, me and my teammates wanted to do our next experiment which is making online WiFi and web-based weather station using ESP32 and BME280.</p><p>So here is the list of tools that I needed:</p><ol><li>ESP32</li><li>Arduino IDE</li><li>Jumper cables</li><li>BME280</li><li>MicroUSB-USB connector</li><li>BME280-converter (6 pins)</li></ol><p>After preparing the needed tools, we configured the sensor and ESP32 as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*NPqlmD2XxHPIUmp1_KMcRQ.jpeg" /><figcaption>Configuration</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*QSMI5qbb6GX4P-MXJKNT4Q.jpeg" /><figcaption>Real Configuration</figcaption></figure><p>After that, we have to connect the device that was used to write code in (Arduino IDE) to a WiFi, and have to remember the SSID and password to put them on the code that will be deployed.</p><p>And the code that we deployed is as follows:</p><p>And of course as I said before, we wrote the WiFi SSID and password accordingly.</p><pre>// Load Wi-Fi library<br>#include &lt;WiFi.h&gt;<br>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_BME280.h&gt;<br>#include &lt;Adafruit_Sensor.h&gt;<br><br>//uncomment the following lines if you&#39;re using SPI<br>/*#include &lt;SPI.h&gt;<br>#define BME_SCK 18<br>#define BME_MISO 19<br>#define BME_MOSI 23<br>#define BME_CS 5*/<br><br>#define SEALEVELPRESSURE_HPA (1013.25)<br><br>Adafruit_BME280 bme; // I2C<br>//Adafruit_BME280 bme(BME_CS); // hardware SPI<br>//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI<br><br>// Replace with your network credentials<br>const char* ssid     = &quot;nemangkawi&quot;;<br>const char* password = &quot;12345678&quot;;<br><br>// Set web server port number to 80<br>WiFiServer server(80);<br><br>// Variable to store the HTTP request<br>String header;<br><br>void setup() {<br>  Serial.begin(115200);<br>  bool status;<br><br>  // default settings<br>  // (you can also pass in a Wire library object like &amp;Wire2)<br>  //status = bme.begin();  <br>  if (!bme.begin(0x76)) {<br>    Serial.println(&quot;Could not find a valid BME280 sensor, check wiring!&quot;);<br>    while (1);<br>  }<br><br>  // Connect to Wi-Fi network with SSID and password<br>  Serial.print(&quot;Connecting to &quot;);<br>  Serial.println(ssid);<br>  WiFi.begin(ssid, password);<br>  while (WiFi.status() != WL_CONNECTED) {<br>    delay(500);<br>    Serial.print(&quot;.&quot;);<br>  }<br>  // Print local IP address and start web server<br>  Serial.println(&quot;&quot;);<br>  Serial.println(&quot;WiFi connected.&quot;);<br>  Serial.println(&quot;IP address: &quot;);<br>  Serial.println(WiFi.localIP());<br>  server.begin();<br>}<br><br>void loop(){<br>  WiFiClient client = server.available();   // Listen for incoming clients<br><br>  if (client) {                             // If a new client connects,<br>    Serial.println(&quot;New Client.&quot;);          // print a message out in the serial port<br>    String currentLine = &quot;&quot;;                // make a String to hold incoming data from the client<br>    while (client.connected()) {            // loop while the client&#39;s connected<br>      if (client.available()) {             // if there&#39;s bytes to read from the client,<br>        char c = client.read();             // read a byte, then<br>        Serial.write(c);                    // print it out the serial monitor<br>        header += c;<br>        if (c == &#39;\n&#39;) {                    // if the byte is a newline character<br>          // if the current line is blank, you got two newline characters in a row.<br>          // that&#39;s the end of the client HTTP request, so send a response:<br>          if (currentLine.length() == 0) {<br>            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)<br>            // and a content-type so the client knows what&#39;s coming, then a blank line:<br>            client.println(&quot;HTTP/1.1 200 OK&quot;);<br>            client.println(&quot;Content-type:text/html&quot;);<br>            client.println(&quot;Connection: close&quot;);<br>            client.println();<br>            <br>            // Display the HTML web page<br>            client.println(&quot;&lt;!DOCTYPE html&gt;&lt;html&gt;&quot;);<br>            client.println(&quot;&lt;head&gt;&lt;meta name=\&quot;viewport\&quot; content=\&quot;width=device-width, initial-scale=1\&quot;&gt;&quot;);<br>            client.println(&quot;&lt;link rel=\&quot;icon\&quot; href=\&quot;data:,\&quot;&gt;&quot;);<br>            // CSS to style the table <br>            client.println(&quot;&lt;style&gt;body { text-align: center; font-family: \&quot;Trebuchet MS\&quot;, Arial;}&quot;);<br>            client.println(&quot;table { border-collapse: collapse; width:35%; margin-left:auto; margin-right:auto; }&quot;);<br>            client.println(&quot;th { padding: 12px; background-color: #0043af; color: white; }&quot;);<br>            client.println(&quot;tr { border: 1px solid #ddd; padding: 12px; }&quot;);<br>            client.println(&quot;tr:hover { background-color: #bcbcbc; }&quot;);<br>            client.println(&quot;td { border: none; padding: 12px; }&quot;);<br>            client.println(&quot;.sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px; }&quot;);<br>            <br>            // Web Page Heading<br>            client.println(&quot;&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;ESP32 with BME280&lt;/h1&gt;&quot;);<br>            client.println(&quot;&lt;table&gt;&lt;tr&gt;&lt;th&gt;MEASUREMENT&lt;/th&gt;&lt;th&gt;VALUE&lt;/th&gt;&lt;/tr&gt;&quot;);<br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Temp. Celsius&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(bme.readTemperature());<br>            client.println(&quot; *C&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);  <br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Temp. Fahrenheit&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(1.8 * bme.readTemperature() + 32);<br>            client.println(&quot; *F&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);       <br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Pressure&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(bme.readPressure() / 100.0F);<br>            client.println(&quot; hPa&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);<br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Approx. Altitude&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(bme.readAltitude(SEALEVELPRESSURE_HPA));<br>            client.println(&quot; m&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;); <br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Humidity&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(bme.readHumidity());<br>            client.println(&quot; %&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;); <br>            client.println(&quot;&lt;/body&gt;&lt;/html&gt;&quot;);<br>            <br>            // The HTTP response ends with another blank line<br>            client.println();<br>            // Break out of the while loop<br>            break;<br>          } else { // if you got a newline, then clear currentLine<br>            currentLine = &quot;&quot;;<br>          }<br>        } else if (c != &#39;\r&#39;) {  // if you got anything else but a carriage return character,<br>          currentLine += c;      // add it to the end of the currentLine<br>        }<br>      }<br>    }<br>    // Clear the header variable<br>    header = &quot;&quot;;<br>    // Close the connection<br>    client.stop();<br>    Serial.println(&quot;Client disconnected.&quot;);<br>    Serial.println(&quot;&quot;);<br>  }<br>}</pre><p>Well oh well, apparently, we have to solder the BME-6 pins-converter to the BME280 itself. And this was the hard part. The last time that I soldered things is when I was in junior high school, or about 7–8 years ago. And that was quite some time. I used to be very agile in soldering things, and I was pretty good at it. But I lost it all, and the supposedly-soldered-BME was ruined. It can’t connect and transfer its data to the ESP32.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-xPbkWpHmhe3x1lMyftsA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGyYJAXkZUZh_a0-u5UeZA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMeoHJ5Ad4JLomfG5ahAHw.jpeg" /><figcaption>Failed Soldering Attempt</figcaption></figure><p>As you can see, the BME280 was pretty burned and by that definition we concluded that we ruined the BME280. Of course we’ve tried another trial and error which is making sure that the cables were in and fit. But still, after changing cables and everything, it still showed the same error message.</p><p>Supposedly, the web looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*41o_opQVauesdqDvcKXDNQ.png" /><figcaption>Succeed Attemp</figcaption></figure><p>So yes, we failed on this experiment, and of course me and my teammates wanted to do this experiment nicely and successful, but there is a pandemic going on and we can’t gather and do this experiment together anymore. Since out electrical parts are separated. Doing this experiment alone is of course manageable, and the discussion is still on my team until now.</p><p>So yes, again, thank you for your attention and time reading this failed-experiment, see you on the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3753310e3478" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>