<?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 Snayush on Medium]]></title>
        <description><![CDATA[Stories by Snayush on Medium]]></description>
        <link>https://medium.com/@snayush77?source=rss-76270a7e4e3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1VTaWYhQGRTn1Wnb</url>
            <title>Stories by Snayush on Medium</title>
            <link>https://medium.com/@snayush77?source=rss-76270a7e4e3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:59:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@snayush77/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[Unlocking the Benefits of Google Cloud SQL: A Comprehensive Guide]]></title>
            <link>https://medium.com/@snayush77/unlocking-the-benefits-of-google-cloud-sql-a-comprehensive-guide-a3231a37c135?source=rss-76270a7e4e3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3231a37c135</guid>
            <category><![CDATA[google-cloud-sql]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[data-security]]></category>
            <category><![CDATA[database-management]]></category>
            <dc:creator><![CDATA[Snayush]]></dc:creator>
            <pubDate>Tue, 02 May 2023 03:15:21 GMT</pubDate>
            <atom:updated>2023-05-02T03:15:21.746Z</atom:updated>
            <content:encoded><![CDATA[<p>Google Cloud SQL is a fully-managed database service that provides a reliable, secure, and scalable relational database management system. It is a powerful tool for businesses looking to move their database infrastructure to the cloud, providing many benefits over traditional on-premises solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZL8Kz89syE5bGgqInRb_Q.png" /></figure><p>One of the most significant benefits of using Google Cloud SQL is its fully managed service. With Cloud SQL, you don’t have to worry about managing the underlying infrastructure or backups of your database. Google manages all of this for you, ensuring that your data is safe and always available.</p><p>Another significant advantage of Google Cloud SQL is its scalability. As your business grows, so will your database needs. With Cloud SQL, you can easily increase the capacity of your database by adding more CPU, memory, or storage without any downtime. This flexibility allows you to scale up or down depending on your business needs, saving you money and providing the performance you need.</p><p>Google Cloud SQL also provides high availability and automatic failover. This ensures that your database is always available to your applications, even in the event of an outage. You can configure your instances for automatic backups, point-in-time recovery, and replication to ensure that your data is always protected.</p><p>Security is another significant advantage of Google Cloud SQL. It provides advanced security features such as SSL encryption, private IP, and VPC Service Controls. You can also set up your database with IAM roles and permissions to ensure that only authorized users can access your data.</p><p>Google Cloud SQL integrates seamlessly with other Google Cloud services, such as Compute Engine, Kubernetes Engine, and Cloud Functions. This allows you to build powerful, scalable applications that can handle large amounts of data. You can also easily migrate your existing on-premises databases to Cloud SQL with minimal effort.</p><p>There are many use cases for Google Cloud SQL, including web applications, mobile applications, analytics, and e-commerce platforms. Cloud SQL is an excellent choice for web applications that require a scalable and reliable database. You can easily deploy your web application to Google Cloud Platform and use Cloud SQL as your backend database.</p><p>For mobile applications, Google Cloud SQL can be used to store data, providing a secure and scalable backend for your mobile app. With Cloud SQL, you can easily handle user authentication and data storage for your mobile app.</p><p>Google Cloud SQL can also be used for analytics, storing and analyzing large amounts of data. You can use Cloud SQL to store your data and then analyze it using Google Cloud Dataflow, BigQuery, or other data analytics tools.</p><p>For e-commerce platforms, Google Cloud SQL is a great choice for a scalable and reliable database. You can use Cloud SQL to store your product catalog, customer data, and order history.</p><p>In conclusion, Google Cloud SQL is a powerful and reliable database service that can help your business scale and grow. With its fully managed service, scalability, high availability, security, and integration with other Google Cloud services, Cloud SQL is an excellent choice for businesses looking to move their database infrastructure to the cloud. It can save you time and money while providing the performance and reliability that your applications need. If you are looking for a reliable and scalable database solution for your business, consider Google Cloud SQL.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3231a37c135" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PID Tuning Methods]]></title>
            <link>https://medium.com/@snayush77/pid-tuning-methods-8b3d39e5263c?source=rss-76270a7e4e3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b3d39e5263c</guid>
            <category><![CDATA[idp]]></category>
            <category><![CDATA[tuning]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[ayush]]></category>
            <category><![CDATA[control-system]]></category>
            <dc:creator><![CDATA[Snayush]]></dc:creator>
            <pubDate>Fri, 25 Nov 2022 20:11:01 GMT</pubDate>
            <atom:updated>2022-11-25T20:11:01.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*rc0iv7tRnaQ_Lnc7I1p5lg.png" /></figure><p><strong><em>What is PID Tuning?</em></strong></p><p>PID tuning is the process of finding the values of proportional, integral, and derivative gains of a PID controller to achieve desired performance and meet design requirements.</p><p><strong>So, here are some PID Tuning Methods:</strong></p><p><strong><em>What is heuristic tuning?</em></strong></p><p>A heuristic tuning strategy is one that use broad guidelines to get approximations or qualitative outcomes. For better or worse, these techniques are used to tune the most of PID loops worldwide.</p><p>Heuristic tuning is an example, and the trial-and-error approach is one.</p><p><strong><em>PID tuning approach using trial and error</em></strong></p><p>Once you have a firm grasp of PID settings, the trial-and-error approach is a rather simple one. The parameters are changed in phases, going from proportional to integral to derivative. Typically, you begin with a pre-existing set of parameters and make minor adjustments to them to enhance the response. You begin with a general, secure initial guess for brand-new PID loops.</p><p>Basically, one thinks about: Basically, one considers:</p><p>• To accelerate the response, the P-action is implemented. Oscillation is the outcome of excessive P-action.</p><p>• To get the desired steady-state response, the I-action is introduced. The drawback is a prolonged duration of increased oscillatory reaction.</p><p>• The D-action is added to provide dampening. The drawback is the increased likelihood of oscillation at a high frequency as well as the sensitivity to noise.</p><p>How the approach should be applied is determined by tuning a new or existing closed loop. We go into detail about that in this blog. Tuning a new or existing closed loop determines how the approach should be used. In this blog, we Trial-and-error: the Advantages and cons</p><p>Advantage: It’s a quick and simple technique to get a decent outcome.</p><p>Advantage: It takes an intuitive approach; hence, no implicit assumptions about the process are established.</p><p>Cons: It takes a lot of time. To perform well, it takes a lot of effort.</p><p>Cons: It doesn’t ensure that a solid and stable solution will be found. The entire plant may be at risk from this.</p><p><strong><em>What is rule-based tuning?</em></strong></p><p>Rule-based PID tuning techniques rely on an assumed process response to produce simple mathematical formulas that make it possible to tune a PID controller. Simple experiments can be utilised to derive the process characteristics, which are then used to calculate the PID parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*rQ0Fr4uKhkyKATbUo-xO3A.png" /></figure><p>Be aware that these tuning techniques are sensitive to differences from the presumptive process response (e.g. first order linear model with delay). The real PID performance will be significantly reduced by a significant departure from the predicted process time delay. Additionally, there is very little or no chance to create your own control objectives.</p><p>The PID parameters are described as the parameters of the ISA algorithm or the general PID control algorithm: • Rule-based tuning is relevant for The Ziegler-Nichols, Chien, Hrones and Reswick, Cohen-Coon, Kappa-tau, and Lambda rule-based tuning techniques are popular.</p><p><strong><em>Ziegler-Nichols tuning method</em></strong></p><p>Ziegler-Nichol’s guidelines are frequently used in the sector. These regulations typically produce aggressive control behaviour. A 25% maximum step overrun is the design condition for the Ziegler-Nichols tuning rules.</p><p>The step response method and the frequency response method are two options offered by the Ziegler-Nichols tuning method.</p><p>Response to the Ziegler-Nichols step PID tuning approach</p><p>Only stable processes may be used with this technique. To determine the features of the process, open loop experiments are necessary.</p><p>response to the ziegler-nichols frequency PID tuning approach</p><p>Use of this technique requires a closed loop PID controller. In order to acquire estimated process characteristics, it is necessary to drive the controller to its stability limits. its stability limits in order to obtain estimated process characteristics.</p><p>In general, Ziegler-Nichols performs reasonably well when the dead time is short in comparison to the process time constant. Small variations in the gain or process delay between the estimated and actual values, however, can cause a control loop to become very oscillatory or even unstable.</p><p>Ziegler-Nichol’s method: the pros and cons</p><p>Using Ziegler-Nichols to tune PID loops has its advantages and disadvantages.</p><ul><li>Pro: It’s simple, intuitive and you get a reasonable performance for simple loops.</li><li>Pro: Little process knowledge is required.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Ve_o641y9cOlyvPCkcHurQ.png" /></figure><ul><li>Con: Originally designed for fast disturbance rejection and not for setpoint tracking.</li><li>Con: Results in an oscillatory closed loop response (max overshoot at 25%).</li><li>Con: Only suitable for small dead time processes (dead time is smaller than the process time constant)</li><li>Con: High proportional gains (due to the 25% overshoot design specification), low integral action with too low damping of the closed loop system and too low robustness against changes in the process dynamics, including non-linearities.</li><li>Con: It can’t define control objectives or closed loop performance requirements.</li></ul><p><strong><em>Cohen-Coon tuning method</em></strong></p><p>The Ziegler-Nichols method is the foundation for the Cohen-Coon tuning method, which incorporates more data from your system. Three variables — the steady state gain (a), the time delay (L), and the time constant (T) — define the process. Because more process data is used in this method, control performance is significantly improved.</p><p>Using Cohen-Coon for tuning PID loops has its advantages and disadvantages.</p><ul><li>Pro: Same advantages as Ziegler-Nichols.</li><li>Pro: Additionally, works well specifically for systems with a larger time delay.</li><li>Con: Same disadvantages as Ziegler-Nichols</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*fpbIjKqhXBpY7d7SRmdn4A.png" /></figure><p><strong><em>Kappa-Tau tuning method</em></strong></p><p>The Ziegler-Nichols tuning technique has evolved into the Kappa-tau tuning technique. Ziegler-Nichols has drawbacks, including high proportional gains and rules that perform poorly for systems with a lot of normalised dead time. This approach is intended to address these issues.</p><p>Using Kappa-tau to tune PID loops has its advantages and disadvantages.</p><ul><li>Pro: Less oscillatory response.</li><li>Pro: Originally designed for load disturbance response. It can also deal with setpoint tracking by using setpoint weighting.</li><li>Pro: Results in optimal disturbance rejection with no overshoot.</li><li>Pro: The tuning parameter for the design is the sensitivity of the controller towards process disturbances. Allows choosing between faster or slower response.</li><li>Con: It can’t define control objectives or closed loop performance requirements.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*OIiSjuGUau0_3j6wi9C_wQ.png" /></figure><p><strong><em>Lambda tuning method</em></strong></p><p>The Greek letter lambda () is the source of the name of the Lambda tuning technique. The closed-loop response’s time constant, represented by the parameter, controls how quickly the controller responds. The response features as a tuning parameter and is predicated to follow a first order with delay.</p><p>Using Lambda for tuning PID loops has its advantages and disadvantages.</p><ul><li>Pro: Enables choosing a desired closed-loop time constant, i.e. how fast the controller responds.</li><li>Pro: Works well specifically for systems with a large time delay (dead time is close to the process time constant).</li><li>Pro: Results in high robustness against changes in the process dynamics, including non-linearities.</li><li>Pro: Results in a response with no overshoot.</li><li>Con: Results in a slow rejection of disturbances, especially for slow systems.</li><li>Con: It can’t define control objectives and is limited in closed loop performance requirements.</li><li>Con: Only suited for PI controller tuning. The parameter derivative cannot be taken into consideration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*IERbgMPasChx-zMcj_sFcw.png" /></figure><p>So, this are some methods for PID Tuning I hope you found this Blog helpful for your assignments projects or for some other purpose.</p><p>Don’t forgot to like and follow!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b3d39e5263c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VARIOUS TREE DATA STRUCTURES]]></title>
            <link>https://medium.com/@snayush77/various-tree-data-structures-4b879096aeb3?source=rss-76270a7e4e3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b879096aeb3</guid>
            <category><![CDATA[redandblack]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[trees]]></category>
            <category><![CDATA[parents]]></category>
            <dc:creator><![CDATA[Snayush]]></dc:creator>
            <pubDate>Thu, 30 Jun 2022 02:51:03 GMT</pubDate>
            <atom:updated>2022-06-30T02:51:03.006Z</atom:updated>
            <content:encoded><![CDATA[<p>Data structures are a special way to organize your data and store it on your computer for more effective use. There are different types of data structures. The stack, linked list, and queue are arranged in order. For example, a linked data structure consists of a set of nodes linked by a link or point.</p><p>Similarly, a tree data structure is a type of hierarchical data arranged in a tree-like structure. It consists of a central node, a structural node, and subnodes connected by edges. You can also say that roots, branches, and leaves are interconnected in a tree’s data structure.</p><p><strong><em>The tree is non-linear, a hierarchical data structure consisting of a collection of nodes, and each node in the tree contains a value that is a list of references to the node (the “child”).</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*PZLEPHbPoQVWpEXi" /></figure><p>Types of tree data structure</p><p>The different types of tree data structures are:</p><p><strong>1. General tree</strong></p><p>There is no limit to the number of nodes in a typical tree data structure. This means that the parent node can have any number of child nodes.</p><p><strong>2. Binary tree</strong></p><p>A binary tree node can have up to two child nodes. In a given dendrogram, nodes B, D, and F are children on the left, and E, C, and G are children on the right.</p><p><strong>3. Balance tree</strong></p><p>A tree is said to have a balanced tree data structure if the heights of the left and right subtrees are the same or differ by up to one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*QJ8nRGzTCYnFdN8Q" /><figcaption>BALANCED TREE UNBALANCED TREE</figcaption></figure><p><strong>4. Binary search tree</strong></p><p>As the name implies, the binary search tree is used for various search and sort algorithms. Examples include AVL trees and red-black trees. This is a non-linear data structure. This indicates that the value of the node on the left is smaller than its parent, while the value of the node on the right is greater than its parent.</p><p><strong>Features:</strong></p><p>The properties of the tree data structure are:</p><p>• For n nodes, the edges of the tree are equal (n — 1). For example, as shown in the tree diagram above, five nodes (5–1) contain four edges in the tree data structure.</p><p>• Arrows in the structure represent paths. Each edge connects two nodes.</p><p>• Each of the two nodes or vertices in the tree graph is connected by exactly one edge.</p><p>• Node depth is defined as the length of the path from the root node to node a. The height of node “a” is the longest path from node “a” to the leaf node of the specified tree.</p><p>Other properties are:</p><ul><li>Traversal in the tree is performed by a depth-first search and breadth-first search algorithms. No loops or circuits</li><li>There is no self-loop</li><li>That hierarchical model.</li></ul><p>There are no.of other trees that are implemented in real life scenarios.</p><ol><li><strong>AVL tree</strong></li></ol><p>The AVL tree was invented in 1962 by GM Adelson-Belsky and EM Landis. This tree is named AVL in honor of the inventor.</p><p>An AVL tree can be defined as a height-balanced binary search tree. In this tree, each node is associated with an equilibrium constant calculated by subtracting the height of the subtree on the right from the height of the subtree on the left.</p><p>If the balance factor for each node is between -1 and 1, the tree is considered balanced. Otherwise, the tree is unbalanced and needs to be balanced.</p><p>Balancing factor (k) = height (left (k))-height (right (k))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZwFJzsdBgvYF9STx" /></figure><ol><li><strong>Red-Black tree</strong></li></ol><p>A red-black tree is a self-balancing binary search tree, and each node contains an additional bit that indicates the node’s color (red or black).</p><p>Red-black trees have the following characteristics-</p><ol><li>Each node is color coded either red or black.</li><li>The root node is always black</li><li>Each leaf (NIL) is black.</li><li>If a red node has children, the children are always black. Depth property: For any node, all simple paths from that node to one of its descendants have the same black depth (number of black nodes).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*EU1DjRpFnpuxCTO2" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b879096aeb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PLC programming languages]]></title>
            <link>https://medium.com/@snayush77/plc-programming-languages-6d4ba691e48f?source=rss-76270a7e4e3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d4ba691e48f</guid>
            <dc:creator><![CDATA[Snayush]]></dc:creator>
            <pubDate>Mon, 27 Jun 2022 02:28:03 GMT</pubDate>
            <atom:updated>2022-06-27T02:28:03.021Z</atom:updated>
            <content:encoded><![CDATA[<p>Today in this blog, we are going to see different types of PLC programming languages. What are the most common PLC programming languages that often used most among the programmers?</p><p><strong>Five different types of PLC Programming Languages</strong></p><p>There are five types of PLC Programming languages all are part of <a href="https://en.wikipedia.org/wiki/IEC_61131-3"><em>IEC(International Electrotechnical Commission) 61131–3</em></a> International Standard. According to this standard, the five types of different PLC Programming Languages are:</p><p>1.Ladder Diagram (LD)</p><p>2.Function Block Diagram (FBD)</p><p>3.Structured Text (ST)</p><p>4.Instruction List (IL)</p><p>5.Sequential Function Chart (SFC)</p><p>These are all the five different types of PLC programming languages but among all of them, <strong>Ladder Diagram (LD)</strong> is the most popular PLC programming language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*DItoFJNqInVnFaTaaQFOsQ.png" /><figcaption>Different Types of PLC Programming Languages</figcaption></figure><p>Let’s see all these languages in detail one by one.</p><h3>1) Ladder Diagram (LD)</h3><p>A ladder diagram is usually called a “Ladder Logic”, this represents a program by a graphical diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*iZ7QWNhSa_18r9pYHontHA.png" /></figure><p>This looks like relay racks, each device in the relay rack would be represented by a symbol on the ladder diagram.</p><p>The name ladder diagram is based on the programming language pattern similar to a ladder, with two vertical rails that shows electrical connection among a series of horizontal rungs between them.</p><p><strong>Advantages of Ladder Diagram (LD):</strong></p><p>· Easy to learn, understand and follow</p><p>· More reliable than electronic circuit controller</p><p>· A most convenient way to represent the discrete logic</p><p>· Easy to fault diagnose</p><h3>2) Function Block Diagram (FBD)</h3><p>Function Block Diagram (FBD) is another PLC programming language that is a popular one and looks like a graphical type like a Ladder Diagram (LD).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*hWEP8t4Mxbn3R7TcAQogWQ.png" /></figure><p>In Function Block Diagram inputs and outputs are connected in blocks by connection lines.</p><p>Function blocks are mainly used to do repetitive tasks like starters, closed-loop control, PID loops, etc.</p><p><strong>Advantages of Function Block Diagram (FBD):</strong></p><p>· Easier because of a graphical representation method</p><p>· One block consists of several lines of logic which is like a repetitive task</p><h3>3) Structured Text (ST)</h3><p>The <strong>ST</strong> or <strong>STX</strong> is the short abbreviation of Structured Text, one of the PLC programming languages. It is a high-level programming language is like a ‘C’ or ‘Pascal’.</p><p>The ST consists of various statements with complex statements and instructions like IF, WHILE, CASE, RETURN, FOR, REPEAT, etc.</p><p>It is a very powerful language that can easily execute complex mathematical logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*3OmsQ02ZC6blD7dkLPdglg.png" /></figure><p><strong>Advantages of Structured Text (ST):</strong></p><p>· Very good with complex algorithms and mathematical logic.</p><p>· Easy to modify programming due to standard coding format.</p><h3>4) Instruction List (IL)</h3><p>Instruction List (IL) is one of the PLC programming languages which is like an assembly programming language. You will find the series of instruction lists in this language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*efmzGzMm-HI_ocsKTCRvCA.png" /></figure><p>The mnemonic codes like LD, AND, OR, A, etc. are used in this PLC programming language. Sometimes it is easy to remember the code while using this programming language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*j17gqEQeEJw5iQqFXmIYaw.png" /></figure><p><strong>Advantages of Instruction List (IL):</strong></p><p>· High Execution Speed.</p><p>· Less Memory Consumption as compared to other PLC programming languages.</p><h3>5) Sequential Function Chart (SFC)</h3><p>Sequential Function Chart (SFC) is also a graphical programming language that is like a flow chart like logic.</p><p>In this PLC programming language, the program is divided into steps that act as a major role.</p><p>Steps consist of an action that occurs when a programmer wants them to happen. Steps can be active or inactive.</p><p>Transitions are the instructions that are used to move the program from one step to another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*TY8LXIKxaCyL8GIW1-15aw.png" /></figure><p><strong>Advantages of Sequential Function Chart (SFC)</strong></p><p>· Easy to understand overall program control.</p><p>· Easy to design and modify logic due to repeated instructions.</p><h3>How to choose which PLC programming language to learn?</h3><p>The answer to this question is going to depend on a couple of things:</p><p>1. What language your workplace or lab uses currently.</p><p>2. The application you’re designing.</p><p>3. The PLC brand you have, and the software packages you have access to; and</p><p>4. Your career scenario.</p><p>Let’s look at each of these points in more depth.</p><h3>1. What PLC language your workplace uses</h3><p>à Typically, if you work in a factory or in a lab with PLCs, there’s already a universal language that everyone is expected to use. Most of the time it’s Ladder Diagram, regardless of the application. If you’re getting into PLCs because your job demands it, I highly recommend figuring out what language(s) the equipment uses already and then becoming familiar with those first. It doesn’t make sense to learn ST if all of your machines run LD.</p><h3>2. The Automation Application you’re designing</h3><p>à Secondly, if you work for an Automation, a Systems, or a Machine Integrator, you might be required to know all five IEC 61131–3 languages and choose the best one based on the customer’s application. As mentioned above, each of the PLC programming languages has its advantages and disadvantages depending on what you’re trying to do. Some customers might require that their machine is written in a certain PLC programming language so that their maintenance staff can debug and maintain the equipment after it’s installed. It’s a good idea to check with the contract requirements to ensure that you’re writing the code in the correct language.</p><h3>3. The PLC brand you’re using</h3><p>à Lastly, if you’ll want to figure out what PLC you’re using and what language(s) it supports. Some PLCs only play nice with Ladder Diagram. Some PLCs and PACs support all five IEC 61131–3 languages. Even if your controller supports the language, you’ll want to make sure that your programming software has the capability to write that language. Ladder Diagram is a default option, the majority of the time. Some brands require add-on packs for using additional languages. Consult with the software and your brand’s documentation to figure out which language is best suited for your system.</p><h3>4. Your Career Path</h3><p>Furthermore, if none of those points are applicable to you because you’re just trying to advance (or start) your PLC programming career, then I recommend learning the <a href="https://www.learnrobotics.org/blog/learn-plc-programming/">most popular PLC languages</a> (LD, FBD, ST) and then working your way through Instruction List and Sequential Function Chart. You don’t need to be a master at every PLC language. If you know LD very well, then you’ll be ready to tackle about 80% of the automation projects out there today. It’s more about having a solid foundation in how to develop an automated system. Translating it into a different language is secondary, so long as you understand at least one language very well.</p><h3>Places to Learn PLC Programming</h3><p>There are a bunch of resources to learn PLC programming including vendor training, online courses, and YouTube. Vendor training can be thousands of dollars, so if you’re looking to fund your own PLC development plan, I recommend a few Udemy Courses to get you started</p><h3>Final Thoughts</h3><p>This is all the basic information about different types of PLC programming languages. So, which is the best PLC programming language as per your opinion? Let me know in the comment section.</p><p>As per most of the programmers and users of PLC, Ladder Diagram is the most popular and used PLC programming language due to its easy understanding and similarity to relay logic.</p><p>Please let me know your experience with the different types of PLC programming languages and share your opinion about PLC programming.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d4ba691e48f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Application layer protocols]]></title>
            <link>https://medium.com/@snayush77/application-layer-protocols-c8ed799fb957?source=rss-76270a7e4e3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8ed799fb957</guid>
            <dc:creator><![CDATA[Snayush]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 06:00:25 GMT</pubDate>
            <atom:updated>2022-06-14T06:00:25.318Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog is about protocols used in one of the layers in OSI model which is Application layer. It has all the information about the protocols. But, before that lets see what is meant by OSI model.</p><p><strong>What Is the OSI Model</strong></p><p>The Open Systems Interconnection (OSI) model describes seven layers that computer systems uses to communicate over a network. It was the first standard model for network communications, adopted by all major computer and telecommunication companies in the early 1980s</p><p>The modern Internet is not based on OSI, but on the simpler TCP/IP model. However, the OSI 7-layer model is still widely used, as it helps visualize and communicate how networks operate, and helps isolate and troubleshoot networking problems.</p><p><strong>OSI Model : The OSI 7 Layers</strong></p><p>At the very top of the OSI Reference Model stack of layers, we find the Application layer which is implemented by the network applications. These applications produce the data, which must be transferred over the network. This layer also serves as a window for the application services to access the network and for displaying the received information to the user.</p><p>Example: Application — Browsers, Skype Messenger, etc.</p><p>Application layer is the last and 7th layer of the OSI model. This layer is the abstraction layer, which handles the sharing protocols over the computer network with OSI and TCP/IP model. In internet protocol suite, the application layer contains communication protocols and interface methods which used for the process-to-process communication over the network. Application layer contains several protocols namely Telnet, FTP, TFTP, SMTP, SNMP, DNS, and DHCP.</p><p><strong>Protocols of Application layer</strong></p><p>Below is the list of applications layers protocols.</p><p><strong>1. Telnet</strong></p><p>Telnet is an application protocol. It provides bidirectional interactive text orientated communication feature. For text orientated communication telnet uses terminal connection. Configuration elements of networking hardware can be achieved using telnet. At TCP, information is interspersed in-band with Telnet control information in an 8-bit byte-oriented data connection. Telnet is a type of client server protocol, used to open command line on remote computers.</p><p><strong>2. FTP</strong></p><p>FTP stands for File Transfer Protocol. It is a application layer protocol that is used for transforming a file from one location to another, i.e. from one host to another host. It is a standard mechanism that is provided by TCP/IP. Transforming files from one system to another seems very simple, but some problems need to be dealt with before transforming files. It uses TCP services. It needs two TCP connections. One is a Control connection, and another is a Data connection. For control connection, it uses well-known port 21, and for data connection, it uses well-known port 20.</p><p><strong>3. TFTP</strong></p><p>TFTP stands for Trivial File Transfer Protocol is a application layer protocol, used for sending a file from the server to the client. Trivial File Transfer Protocol uses the concept of UDP to share files between server and client. Here UDP stands for User Datagram Protocol. It is generally used for communicating files among machines set up in the local intranet only. Trivial File Transfer Protocol’s most important feature is that it uses a minimal amount of memory. This application layer Protocol could be used to communicate boot files if computers do not have hard disks. It generally uses protocol 69; however, the port used for communication could be defined by used when Trivial File Transfer Protocol is being set up.</p><p><strong>4. SMTP</strong></p><p>SMTP stands for Simple mail transfer protocol is used to transfer the mails. It defines how both commands and responses must be sent back and forth. It is used two times, between the sender and the sender’s mail server and between the two mail servers. To transfer messages between Messages Transfer Agents client and message transfer agents sever, simple mail transfer protocol uses commands and responses. The actual mail transfer is done through MTA, i.e., Message Transfer Agents. The system must have the client message transfer agents and server message transfer agents to transfer mail from one system to another.</p><p><strong>5. SNMP</strong></p><p>SNMP stands for Simple network management protocol which is used to collect and organize the data of managed devices on IP networks. It also modifies the information to change the behavior of the devices. SNMP is mainly used to monitor and manage the network. It consists of a set of standards for network management, including an application layer protocol, a database schema, and a set of data objects.</p><p><strong>6. DNS</strong></p><p>DNS stands for Domain Name System is a decentralized naming system for the computers and other devices on the internet to translate the domain name of the devices connected on the internet or any other private network to the numerical IP addresses and vice versa. Advantage of DNS is that the user does not need to remember the IP address of the domain. DNS support TCP protocol and UDP protocol. DNS server works on the port 53.Domains are categorized into three parts generic domains, country domains, and inverse domains, where generic domains define registered hosts according to their generic behavior, country domains use two characters country abbreviation, inverse domain maps address to map.</p><p><strong>7. DHCP</strong></p><p>DHCP stands for Dynamic Host Configuration Protocol. It is a network management protocol present in the application layer. With its help, an Internet Protocol IP address can be assigned to any device or node on a network dynamically so that they can communicate using this IP. The main goal of DHCP protocol is to assign unique IP addresses to the hosts. Apart from Unique IP address, it also provides other network address such as subnet mask, Router address, vendor class identifier, and DNS address. A DHCP server has a pool of addresses for a device to get a valid network connection.</p><p><strong>8. NFS:</strong></p><p>It stands for a network file system. It allows remote hosts to mount file systems over a network and interact with those file systems as though they are mounted locally. This enables system administrators to consolidate resources onto centralized servers on the network. The Port number for NFS is 2049.</p><p><strong>9. X window:</strong></p><p>It defines a protocol for the writing of graphical user interface–based client/server applications. The idea is to allow a program, called a client, to run on one computer. It is primarily used in networks of interconnected mainframes. Port number for X window starts from 6000 and increases by 1 for each server.</p><p><strong>10. LPD:</strong></p><p>It stands for Line Printer Daemon. It is designed for printer sharing. It is the part that receives and processes the request. A “daemon” is a server or agent. The Port number for LPD is 515.</p><p>References:-</p><p><a href="https://www.geeksforgeeks.org/protocols-application-layer/"><strong>Protocols in Application Layer — GeeksforGeeks</strong></a></p><p><a href="https://www.geeksforgeeks.org/protocols-application-layer/">The application layer is present at the top of the OSI model. It is the layer through which users interact. It provides…</a></p><p><a href="https://www.geeksforgeeks.org/protocols-application-layer/">www.geeksforgeeks.org</a></p><p><a href="https://study.com/academy/lesson/application-layer-protocols-types-uses.html">https://study.com/academy/lesson/application-layer-protocols-types-uses.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8ed799fb957" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Websocket Programming in ESP32 and ESP8266]]></title>
            <link>https://medium.com/@snayush77/websocket-programming-in-esp32-and-esp8266-5f8cc318a2d0?source=rss-76270a7e4e3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f8cc318a2d0</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[esp32-tutorial]]></category>
            <category><![CDATA[esp32]]></category>
            <dc:creator><![CDATA[Snayush]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 04:22:32 GMT</pubDate>
            <atom:updated>2022-06-14T04:22:32.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_2zFP7zXHSTyWWUC.jpg" /></figure><h3><strong>Definition</strong></h3><p><strong>WebSocket</strong> is a computer communications protocol, giving full-duplex communication channels over a single TCP connection.</p><p>Not quite like HTTP, WebSocket provides full-duplex communication. Moreover, WebSocket allows streams of messages on top of TCP. TCP alone handles streams of bytes without inherent concept of a message.</p><p>So with WebSocket you can do a full-duplex communication, and by subscribing to a channel, you can avoid polling. This protocol is used in a lot of applications, and they will become the future of modern applications.</p><h3>Architecture</h3><p>Basically, you have a server that shares a particular service, and a set of clients that can <strong>connect</strong> to the server.</p><p>The connection creates a channel from the devices, but to obtain information you must <strong>subscribe </strong>to a topic (sometimes subscription is implicit with connection).</p><p>The big difference from REST server is that in an http request you send request and you must wait response to have data and start a new request on the same connection, with the WS you can stream requests and stream responses and then operate whenever you want.</p><p>But how can we use the WebSocket in our projects?<br> A classic example is a table with a lot of rows, first we make a REST call and get all the data of the table, but to update a single cell we use WebSocket subscription, and with JavaScript go to update single cell alongside having a nice graphic effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*mwmppzs6Jh6jiEdZH3qyzg.png" /></figure><h3>WebSocket client</h3><p>Now we are going to see a simple WebSocket client, that are going to connect to a WebSocket echo server. Its behaviour is pretty simple, you send a message and the server replies with the same message, so you can test the send and the receive of your Client.</p><h4>JavaScript WebSocket client</h4><p>Here is a simplified version of WebSocket test client</p><p>&lt;! —</p><p>js simple WebSocket client</p><p>I use the ws://echo.websocket.org/ echo server</p><p>When you send a message to this server you receive</p><p>a response with the same message</p><p>→</p><p>&lt;!DOCTYPE html&gt;</p><p>&lt;html&gt;</p><p>&lt;head&gt;</p><p>&lt;meta charset=”utf-8&quot;/&gt;</p><p>&lt;title&gt;WebSocket Test&lt;/title&gt;</p><p>&lt;style&gt;</p><p>#output {</p><p>border: solid 1px #999999;</p><p>border-top-color: #CCCCCC;</p><p>border-left-color: #CCCCCC;</p><p>padding: 5px;</p><p>width: 300px;</p><p>height: 172px;</p><p>overflow-y: scroll;</p><p>font-family: “Open Sans”;</p><p>font-size: 13px;</p><p>}</p><p>&lt;/style&gt;</p><p>&lt;script language=”javascript” type=”text/javascript”&gt;</p><p>var wsUri = “wss://echo.websocket.org/”;</p><p>var output;</p><p>function init() {</p><p>output = document.getElementById(“output”);</p><p>testWebSocket();</p><p>}</p><p>function testWebSocket() {</p><p>websocket = new WebSocket(wsUri);</p><p>websocket.onopen = function (evt) {</p><p>onOpen(evt)</p><p>};</p><p>websocket.onclose = function (evt) {</p><p>onClose(evt)</p><p>};</p><p>websocket.onmessage = function (evt) {</p><p>onMessage(evt)</p><p>};</p><p>websocket.onerror = function (evt) {</p><p>onError(evt)</p><p>};</p><p>}</p><p>function onOpen(evt) {</p><p>writeToScreen(“CONNECTED”);</p><p>// doSend(“Hi, I’m a simple Ayush JS client!!”);</p><p>}</p><p>function onClose(evt) {</p><p>writeToScreen(“DISCONNECTED”);</p><p>}</p><p>function onMessage(evt) {</p><p>writeToScreen(‘&lt;span style=”color: blue;”&gt;RESPONSE: ‘ + evt.data + ‘&lt;/span&gt;’);</p><p>// websocket.close();</p><p>}</p><p>function onError(evt) {</p><p>writeToScreen(‘&lt;span style=”color: red;”&gt;ERROR:&lt;/span&gt; ‘ + evt.data);</p><p>}</p><p>function doSend(message) {</p><p>writeToScreen(“SENT: “ + message);</p><p>websocket.send(message);</p><p>}</p><p>function writeToScreen(message) {</p><p>var pre = document.createElement(“p”);</p><p>pre.style.wordWrap = “break-word”;</p><p>pre.innerHTML = message;</p><p>output.appendChild(pre);</p><p>output.scrollTop = output.scrollHeight;</p><p>}</p><p>window.addEventListener(“load”, init, false);</p><p>&lt;/script&gt;</p><p>&lt;/head&gt;</p><p>&lt;body&gt;</p><p>&lt;h2&gt;WebSocket Test&lt;/h2&gt;</p><p>&lt;div id=”output”&gt;&lt;/div&gt;</p><p>&lt;br/&gt;</p><p>&lt;input type=”button” value=”Send message!” onclick=”doSend(‘Simple Ayush js client message!!’)”/&gt;&lt;/div&gt;</p><p>&lt;input type=”button” value=”Close connection!” onclick=”websocket.close()”/&gt;&lt;/div&gt;</p><p>&lt;/body&gt;</p><p>&lt;/html&gt;</p><p>The important part of the code is</p><p>function testWebSocket() {</p><p>websocket = new WebSocket(wsUri);</p><p>websocket.onopen = function (evt) {</p><p>onOpen(evt)</p><p>};</p><p>websocket.onclose = function (evt) {</p><p>onClose(evt)</p><p>};</p><p>websocket.onmessage = function (evt) {</p><p>onMessage(evt)</p><p>};</p><p>websocket.onerror = function (evt) {</p><p>onError(evt)</p><p>};</p><p>}</p><p>This is a simple code to establish a connection, and attach a series of callback functions to specified events:</p><p>§ <strong>onopen</strong>: this is called when a connection is established;</p><p>§ <strong>onclose</strong>: this is called when a client is disconnected;</p><p>§ <strong>onmessage</strong>: this is called here when a message has arrived;</p><p>§ <strong>onerror</strong>: this is called when an error is generated.</p><p>As you can see to send message you must simply call websocket.send after the connection.</p><h3>Library</h3><p>You can find the library directly in the Arduino libraries repository (Tools --&gt; Manage libraries..).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*BBsNxnod5UxM3CdpfpRLvA.png" /></figure><p>Pay attention for esp8266 and esp32 you must use 2.x.x version.</p><h4>esp8266 WebSocket client</h4><p>To connect with your esp8266 the code is quite simple</p><p>/*</p><p>* esp8266 simple WebSocket client</p><p>*</p><p>* I use the ws://echo.websocket.org/ echo server</p><p>* When you send a message to this server you receive</p><p>* a response with the same message</p><p>*</p><p>*/</p><p>#include &lt;Arduino.h&gt;</p><p>#include &lt;ESP8266WiFi.h&gt;</p><p>#include &lt;WebSocketsClient.h&gt;</p><p>WebSocketsClient webSocket;</p><p>const char *ssid = “&lt;YOUR-SSID&gt;”;</p><p>const char *password = “&lt;YOUR-PASSWD&gt;”;</p><p>unsigned long messageInterval = 5000;</p><p>bool connected = false;</p><p>#define DEBUG_SERIAL Serial</p><p>void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {</p><p>switch(type) {</p><p>case WStype_DISCONNECTED:</p><p>DEBUG_SERIAL.printf(“[WSc] Disconnected!\n”);</p><p>connected = false;</p><p>break;</p><p>case WStype_CONNECTED: {</p><p>DEBUG_SERIAL.printf(“[WSc] Connected to url: %s\n”, payload);</p><p>connected = true;</p><p>// send message to server when Connected</p><p>DEBUG_SERIAL.println(“[WSc] SENT: Connected”);</p><p>webSocket.sendTXT(“Connected”);</p><p>}</p><p>break;</p><p>case WStype_TEXT:</p><p>DEBUG_SERIAL.printf(“[WSc] RESPONSE: %s\n”, payload);</p><p>break;</p><p>case WStype_BIN:</p><p>DEBUG_SERIAL.printf(“[WSc] get binary length: %u\n”, length);</p><p>hexdump(payload, length);</p><p>break;</p><p>case WStype_PING:</p><p>// pong will be send automatically</p><p>DEBUG_SERIAL.printf(“[WSc] get ping\n”);</p><p>break;</p><p>case WStype_PONG:</p><p>// answer to a ping we send</p><p>DEBUG_SERIAL.printf(“[WSc] get pong\n”);</p><p>break;</p><p>}</p><p>}</p><p>void setup() {</p><p>DEBUG_SERIAL.begin(115200);</p><p>// DEBUG_SERIAL.setDebugOutput(true);</p><p>DEBUG_SERIAL.println();</p><p>DEBUG_SERIAL.println();</p><p>DEBUG_SERIAL.println();</p><p>for(uint8_t t = 4; t &gt; 0; t — ) {</p><p>DEBUG_SERIAL.printf(“[SETUP] BOOT WAIT %d…\n”, t);</p><p>DEBUG_SERIAL.flush();</p><p>delay(1000);</p><p>}</p><p>WiFi.begin(ssid, password);</p><p>while ( WiFi.status() != WL_CONNECTED ) {</p><p>delay ( 500 );</p><p>Serial.print ( “.” );</p><p>}</p><p>DEBUG_SERIAL.print(“Local IP: “); DEBUG_SERIAL.println(WiFi.localIP());</p><p>// server address, port and URL</p><p>webSocket.begin(“echo.websocket.org”, 80, “/”);</p><p>// event handler</p><p>webSocket.onEvent(webSocketEvent);</p><p>}</p><p>unsigned long lastUpdate = millis();</p><p>void loop() {</p><p>webSocket.loop();</p><p>if (connected &amp;&amp; lastUpdate+messageInterval&lt;millis()){</p><p>DEBUG_SERIAL.println(“[WSc] SENT: Simple js client message!!”);</p><p>webSocket.sendTXT(“Simple Ayush js client message!!”);</p><p>lastUpdate = millis();</p><p>}</p><p>}</p><p>The core part is:</p><p>switch(type) {</p><p>case WStype_DISCONNECTED:</p><p>DEBUG_SERIAL.printf(“[WSc] Disconnected!\n”);</p><p>connected = false;</p><p>break;</p><p>case WStype_CONNECTED: {</p><p>DEBUG_SERIAL.printf(“[WSc] Connected to url: %s\n”, payload);</p><p>connected = true;</p><p>// send message to server when Connected</p><p>DEBUG_SERIAL.println(“[WSc] SENT: Connected”);</p><p>webSocket.sendTXT(“Connected”);</p><p>}</p><p>break;</p><p>case WStype_TEXT:</p><p>DEBUG_SERIAL.printf(“[WSc] RESPONSE: %s\n”, payload);</p><p>break;</p><p>case WStype_BIN:</p><p>DEBUG_SERIAL.printf(“[WSc] get binary length: %u\n”, length);</p><p>hexdump(payload, length);</p><p>break;</p><p>case WStype_PING:</p><p>// pong will be send automatically</p><p>DEBUG_SERIAL.printf(“[WSc] get ping\n”);</p><p>break;</p><p>case WStype_PONG:</p><p>// answer to a ping we send</p><p>DEBUG_SERIAL.printf(“[WSc] get pong\n”);</p><p>break;</p><p>}</p><p>§ <strong>WStype_CONNECTED</strong>: when connection is established;</p><p>§ <strong>WStype_DISCONNECTED</strong>: when the client is disconnected;</p><p>§ <strong>WStype_TEXT</strong>: when a text message arrives;</p><p>§ <strong>WStype_BIN</strong>: when a binary message arrives;</p><p>§ <strong>WStype_PING </strong>and <strong>WStype_PONG</strong>: here used as the “keep-alive” message.</p><p>To connect you must use this command:</p><p>// server address, port and URL</p><p>webSocket.begin(“echo.websocket.org”, 80, “/”);</p><p>and with webSocket.onEvent we attach the callback to the events.</p><p>With the client to send a simple message we use webSocket.sendTXT.</p><p>As we can see the management of WS is quite simple and similar in all languages.</p><h4>esp32 WebSocket client</h4><p>The esp32 version is quite similar to the esp8266 version.</p><p>/*</p><p>* esp32 simple WebSocket client</p><p>*</p><p>* I used the ws://echo.websocket.org/ echo server</p><p>* When you send a message to this server you receive</p><p>* a response with the same message</p><p>*</p><p>*/</p><p>#include &lt;Arduino.h&gt;</p><p>#include &lt;WiFi.h&gt;</p><p>#include &lt;WebSocketsClient.h&gt;</p><p>WebSocketsClient webSocket;</p><p>const char *ssid = “&lt;YOUR-SSID&gt;”;</p><p>const char *password = “&lt;YOUR-PASSWD&gt;”;</p><p>unsigned long messageInterval = 5000;</p><p>bool connected = false;</p><p>#define DEBUG_SERIAL Serial</p><p>void hexdump(const void *mem, uint32_t len, uint8_t cols = 16) {</p><p>const uint8_t* src = (const uint8_t*) mem;</p><p>DEBUG_SERIAL.printf(“\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)”, (ptrdiff_t)src, len, len);</p><p>for(uint32_t i = 0; i &lt; len; i++) {</p><p>if(i % cols == 0) {</p><p>DEBUG_SERIAL.printf(“\n[0x%08X] 0x%08X: “, (ptrdiff_t)src, i);</p><p>}</p><p>DEBUG_SERIAL.printf(“%02X “, *src);</p><p>src++;</p><p>}</p><p>DEBUG_SERIAL.printf(“\n”);</p><p>}</p><p>void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {</p><p>switch(type) {</p><p>case WStype_DISCONNECTED:</p><p>DEBUG_SERIAL.printf(“[WSc] Disconnected!\n”);</p><p>connected = false;</p><p>break;</p><p>case WStype_CONNECTED: {</p><p>DEBUG_SERIAL.printf(“[WSc] Connected to url: %s\n”, payload);</p><p>connected = true;</p><p>// send message to server when Connected</p><p>DEBUG_SERIAL.println(“[WSc] SENT: Connected”);</p><p>webSocket.sendTXT(“Connected”);</p><p>}</p><p>break;</p><p>case WStype_TEXT:</p><p>DEBUG_SERIAL.printf(“[WSc] RESPONSE: %s\n”, payload);</p><p>break;</p><p>case WStype_BIN:</p><p>DEBUG_SERIAL.printf(“[WSc] get binary length: %u\n”, length);</p><p>hexdump(payload, length);</p><p>break;</p><p>case WStype_PING:</p><p>// pong will be send automatically</p><p>DEBUG_SERIAL.printf(“[WSc] get ping\n”);</p><p>break;</p><p>case WStype_PONG:</p><p>// answer to a ping we send</p><p>DEBUG_SERIAL.printf(“[WSc] get pong\n”);</p><p>break;</p><p>case WStype_ERROR:</p><p>case WStype_FRAGMENT_TEXT_START:</p><p>case WStype_FRAGMENT_BIN_START:</p><p>case WStype_FRAGMENT:</p><p>case WStype_FRAGMENT_FIN:</p><p>break;</p><p>}</p><p>}</p><p>void setup() {</p><p>DEBUG_SERIAL.begin(115200);</p><p>// DEBUG_SERIAL.setDebugOutput(true);</p><p>DEBUG_SERIAL.println();</p><p>DEBUG_SERIAL.println();</p><p>DEBUG_SERIAL.println();</p><p>for(uint8_t t = 4; t &gt; 0; t — ) {</p><p>DEBUG_SERIAL.printf(“[SETUP] BOOT WAIT %d…\n”, t);</p><p>DEBUG_SERIAL.flush();</p><p>delay(1000);</p><p>}</p><p>WiFi.begin(ssid, password);</p><p>while ( WiFi.status() != WL_CONNECTED ) {</p><p>delay ( 500 );</p><p>DEBUG_SERIAL.print ( “.” );</p><p>}</p><p>DEBUG_SERIAL.print(“Local IP: “); DEBUG_SERIAL.println(WiFi.localIP());</p><p>// server address, port and URL</p><p>webSocket.begin(“echo.websocket.org”, 80, “/”);</p><p>// event handler</p><p>webSocket.onEvent(webSocketEvent);</p><p>}</p><p>unsigned long lastUpdate = millis();</p><p>void loop() {</p><p>webSocket.loop();</p><p>if (connected &amp;&amp; lastUpdate+messageInterval&lt;millis()){</p><p>DEBUG_SERIAL.println(“[WSc] SENT: Simple Ayush js client message!”);</p><p>webSocket.sendTXT(“Simple Ayush js client message!”);</p><p>lastUpdate = millis();</p><p>}</p><p>}</p><p>But we can immediately identify some differences, in the webSocketEvent we have to pay attention to the hexdump method to decode the binary message and there are a set of case switches that must be implemented (I added them at the end).</p><h4>esp8266 WebSocket server</h4><p>WebSocket server It’s quite alike to the client, we have a series of event to manage the messages and connection status, here’s an example</p><p>/*</p><p>* esp8266 simple WebSocket server</p><p>*</p><p>* The server response with the</p><p>* echo of the message you send</p><p>* and send a broadcast every 5 seconds</p><p>*</p><p>*/</p><p>#include &lt;Arduino.h&gt;</p><p>#include &lt;ESP8266WiFi.h&gt;</p><p>#include &lt;WebSocketsServer.h&gt;</p><p>const char *ssid = “&lt;YOUR-SSID&gt;”;</p><p>const char *password = “&lt;YOUR-PASSWD&gt;”;</p><p>const uint8_t wsPort = 81;</p><p>unsigned long messageInterval = 5000;</p><p>bool connected = false;</p><p>#define DEBUG_SERIAL Serial</p><p>WebSocketsServer webSocket = WebSocketsServer(wsPort);</p><p>void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {</p><p>switch(type) {</p><p>case WStype_DISCONNECTED:</p><p>DEBUG_SERIAL.printf(“[%u] Disconnected!\n”, num);</p><p>break;</p><p>case WStype_CONNECTED:</p><p>{</p><p>IPAddress ip = webSocket.remoteIP(num);</p><p>DEBUG_SERIAL.printf(“[%u] Connected from %d.%d.%d.%d url: %s\n”, num, ip[0], ip[1], ip[2], ip[3], payload);</p><p>// send message to client</p><p>webSocket.sendTXT(num, “Connected”);</p><p>}</p><p>break;</p><p>case WStype_TEXT:</p><p>DEBUG_SERIAL.printf(“[%u] RECEIVE TXT: %s\n”, num, payload);</p><p>// send message to client</p><p>webSocket.sendTXT(num, “(ECHO MESSAGE) “+String((char *)payload));</p><p>// send data to all connected clients</p><p>// webSocket.broadcastTXT(“message here”);</p><p>break;</p><p>case WStype_BIN:</p><p>DEBUG_SERIAL.printf(“[%u] get binary length: %u\n”, num, length);</p><p>hexdump(payload, length);</p><p>// send message to client</p><p>// webSocket.sendBIN(num, payload, length);</p><p>break;</p><p>}</p><p>}</p><p>void setup() {</p><p>DEBUG_SERIAL.begin(115200);</p><p>// DEBUG_SERIAL.setDebugOutput(true);</p><p>DEBUG_SERIAL.println();</p><p>DEBUG_SERIAL.println();</p><p>DEBUG_SERIAL.println();</p><p>for(uint8_t t = 4; t &gt; 0; t — ) {</p><p>DEBUG_SERIAL.printf(“[SETUP] BOOT WAIT %d…\n”, t);</p><p>DEBUG_SERIAL.flush();</p><p>delay(1000);</p><p>}</p><p>WiFi.begin(ssid, password);</p><p>while ( WiFi.status() != WL_CONNECTED ) {</p><p>delay ( 500 );</p><p>Serial.print ( “.” );</p><p>}</p><p>DEBUG_SERIAL.println(“WebSocket complete uri is: “);</p><p>DEBUG_SERIAL.print(“ws://”);</p><p>DEBUG_SERIAL.print(WiFi.localIP());</p><p>DEBUG_SERIAL.print(“:”);</p><p>DEBUG_SERIAL.print(wsPort);</p><p>DEBUG_SERIAL.println(“/”);</p><p>webSocket.begin();</p><p>webSocket.onEvent(webSocketEvent);</p><p>}</p><p>unsigned long lastUpdate = millis();</p><p>void loop() {</p><p>webSocket.loop();</p><p>if (lastUpdate+messageInterval&lt;millis()){</p><p>DEBUG_SERIAL.println(“[WSc] SENT: Simple broadcast client message!!”);</p><p>webSocket.broadcastTXT(“Simple broadcast client message!!”);</p><p>lastUpdate = millis();</p><p>}</p><p>}</p><p>You can grab the ws uri to put on client from Serial output:</p><p>[SETUP] BOOT WAIT 4…</p><p>[SETUP] BOOT WAIT 3…</p><p>[SETUP] BOOT WAIT 2…</p><p>[SETUP] BOOT WAIT 1…</p><p>…..</p><p>WebSocket complete uri is:</p><p>ws://192.168.1.127:81/</p><p>The structure is quite similar to the client, but you must pay attention to:</p><p>When a client is connected, it is associated with an Id and it is possible to use it to send a message to a specific client, an example is the echo message</p><p>// send message to client</p><p>webSocket.sendTXT(num, “(ECHO MESSAGE) “+String((char *)payload));</p><p>To send a message to all the client you can use broadcastTXT:</p><p>webSocket.broadcastTXT(“Simple broadcast client message!!”);</p><h4>esp32 WebSocket server</h4><p>/*</p><p>* esp32 simple WebSocket server</p><p>*</p><p>* The server response with the</p><p>* echo of the message you send</p><p>* and send a broadcast every 5secs</p><p>*</p><p>*/</p><p>#include &lt;Arduino.h&gt;</p><p>#include &lt;WiFi.h&gt;</p><p>#include &lt;WebSocketsServer.h&gt;</p><p>const char *ssid = “&lt;YOUR-SSID&gt;”;</p><p>const char *password = “&lt;YOUR-PASSWD&gt;”;</p><p>const uint8_t wsPort = 81;</p><p>unsigned long messageInterval = 5000;</p><p>bool connected = false;</p><p>#define DEBUG_SERIAL Serial</p><p>WebSocketsServer webSocket = WebSocketsServer(wsPort);</p><p>void hexdump(const void *mem, uint32_t len, uint8_t cols = 16) {</p><p>const uint8_t* src = (const uint8_t*) mem;</p><p>DEBUG_SERIAL.printf(“\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)”, (ptrdiff_t)src, len, len);</p><p>for(uint32_t i = 0; i &lt; len; i++) {</p><p>if(i % cols == 0) {</p><p>DEBUG_SERIAL.printf(“\n[0x%08X] 0x%08X: “, (ptrdiff_t)src, i);</p><p>}</p><p>DEBUG_SERIAL.printf(“%02X “, *src);</p><p>src++;</p><p>}</p><p>DEBUG_SERIAL.printf(“\n”);</p><p>}</p><p>void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {</p><p>switch(type) {</p><p>case WStype_DISCONNECTED:</p><p>DEBUG_SERIAL.printf(“[%u] Disconnected!\n”, num);</p><p>break;</p><p>case WStype_CONNECTED:</p><p>{</p><p>IPAddress ip = webSocket.remoteIP(num);</p><p>DEBUG_SERIAL.printf(“[%u] Connected from %d.%d.%d.%d url: %s\n”, num, ip[0], ip[1], ip[2], ip[3], payload);</p><p>// send message to client</p><p>webSocket.sendTXT(num, “Connected”);</p><p>}</p><p>break;</p><p>case WStype_TEXT:</p><p>DEBUG_SERIAL.printf(“[%u] RECEIVE TXT: %s\n”, num, payload);</p><p>// send message to client</p><p>webSocket.sendTXT(num, “(ECHO MESSAGE) “+String((char *)payload));</p><p>// send data to all connected clients</p><p>// webSocket.broadcastTXT(“message here”);</p><p>break;</p><p>case WStype_BIN:</p><p>DEBUG_SERIAL.printf(“[%u] get binary length: %u\n”, num, length);</p><p>hexdump(payload, length);</p><p>// send message to client</p><p>// webSocket.sendBIN(num, payload, length);</p><p>break;</p><p>case WStype_ERROR:</p><p>case WStype_FRAGMENT_TEXT_START:</p><p>case WStype_FRAGMENT_BIN_START:</p><p>case WStype_FRAGMENT:</p><p>case WStype_FRAGMENT_FIN:</p><p>case WStype_PING:</p><p>case WStype_PONG:</p><p>break;</p><p>}</p><p>}</p><p>void setup() {</p><p>DEBUG_SERIAL.begin(115200);</p><p>// DEBUG_SERIAL.setDebugOutput(true);</p><p>DEBUG_SERIAL.println();</p><p>DEBUG_SERIAL.println();</p><p>DEBUG_SERIAL.println();</p><p>for(uint8_t t = 4; t &gt; 0; t — ) {</p><p>DEBUG_SERIAL.printf(“[SETUP] BOOT WAIT %d…\n”, t);</p><p>DEBUG_SERIAL.flush();</p><p>delay(1000);</p><p>}</p><p>WiFi.begin(ssid, password);</p><p>while ( WiFi.status() != WL_CONNECTED ) {</p><p>delay ( 500 );</p><p>DEBUG_SERIAL.print ( “.” );</p><p>}</p><p>DEBUG_SERIAL.println();DEBUG_SERIAL.println(“WebSocket complete uri is: “);</p><p>DEBUG_SERIAL.print(“ws://”);</p><p>DEBUG_SERIAL.print(WiFi.localIP());</p><p>DEBUG_SERIAL.print(“:”);</p><p>DEBUG_SERIAL.print(wsPort);</p><p>DEBUG_SERIAL.println(“/”);</p><p>webSocket.begin();</p><p>webSocket.onEvent(webSocketEvent);</p><p>}</p><p>unsigned long lastUpdate = millis()+messageInterval;</p><p>void loop() {</p><p>webSocket.loop();</p><p>if (lastUpdate+messageInterval&lt;millis()){</p><p>DEBUG_SERIAL.println(“[WSc] SENT: Simple broadcast client message!!”);</p><p>webSocket.broadcastTXT(“Simple broadcast client message!!”);</p><p>lastUpdate = millis();</p><p>}</p><p>}</p><p>There are a few differences, the WiFi import, the hexdump not implemented natively and some options that are mandatory on the event management switch case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f8cc318a2d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started With Jetpack Compose]]></title>
            <link>https://medium.com/dscvitpune/getting-started-with-jetpack-compose-e799f262ce50?source=rss-76270a7e4e3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e799f262ce50</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Snayush]]></dc:creator>
            <pubDate>Sun, 10 Oct 2021 06:07:16 GMT</pubDate>
            <atom:updated>2021-10-10T06:07:16.487Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CsGmtov-sddFT1eIsyHE6w.png" /></figure><p><strong>Jetpack Compose, </strong>sounds fancy right? Well, it is as fancy as it sounds, being a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will transform your data into a UI hierarchy. When the data changes or is updated then the framework automatically recalls these functions and updates the view for you. In this article, we will see some of the basic topics which are helpful before starting with Jetpack Compose.</p><p>· What is Jetpack Compose?</p><p>· What are its benefits?</p><p>· What challenges we can solve by using Jetpack Compose?</p><p>· How do we get started with Jetpack Compose?</p><p>· Composable Functions</p><p>· Layouts</p><p>· Material Design</p><p>· Lists and Animations</p><p>· Conclusion</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*C6ohr4oleQWb7J-SS1hYtg.png" /></figure><h3>What is Jetpack Compose?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUmh9qYh7iKo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUmh9qYh7iKo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FUmh9qYh7iKo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/324e56c7da8999e8fe0d3de2fee1e6a6/href">https://medium.com/media/324e56c7da8999e8fe0d3de2fee1e6a6/href</a></iframe><p>Less code plus more power to develop. That defines Jetpack Compose perfectly as it is a modern UI toolkit recently launched by Google which is used for building native Android UI. It simplifies and accelerates the UI development with less code, Kotlin APIs, and powerful tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*VRAR5hVg2aIt5GjDJG1tIA.gif" /></figure><h3>What are the Benefits of Using Jetpack Compose?</h3><p>· <strong>Declarative:</strong> It is fully declarative so that you can describe your UI components by calling some predefined functions.</p><p>· <strong>Compatible:</strong> It is easily compatible with the existing views present in Android.</p><p>· <strong>Increase development speed:</strong> Previously developers worked on the XML file and Kotlin file. But with the help of jetpack compose this becomes easy and developers only have to work on the Kotlin files that’s why it will help developers in increasing development speed.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FpcKk8rH9rPzHWh4E23%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FpcKk8rH9rPzHWh4E23%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FpcKk8rH9rPzHWh4E23%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/139e4e57260e529f6754717cb0629057/href">https://medium.com/media/139e4e57260e529f6754717cb0629057/href</a></iframe><p>· <strong>Concise and Idiomatic Kotlin:</strong> Jetpack Compose built the UI with the benefit that Kotlin brings.</p><p>· <strong>Lesser Files:</strong> As the codebase of any application is present in a single file. It becomes easy to manage and handle the codebase of the application.</p><p>· <strong>Written in Kotlin:</strong> The application written using jetpack compose uses only Kotlin programming language.</p><h3>What Challenges Can We Solve using Jetpack Compose?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl1J3ulcILUTKiqCNW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl1J3ulcILUTKiqCNW%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl1J3ulcILUTKiqCNW%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dc56c50fd7db4aca3bacc6001ccd6d9/href">https://medium.com/media/5dc56c50fd7db4aca3bacc6001ccd6d9/href</a></iframe><p>· When writing our code we create multiple methods for different purposes. After that we couple this method in our main function according to our requirement. In Android when building any type of view and setting data to that particular view. First of all, we initialize that view with a variable and then add data to that specific view. This process of grouping UI elements with the View Model is called <strong>Coupling</strong>. When our code is having so many couplings it becomes difficult to maintain this code. So coupling can give you sometimes some errors pertaining to Null References.</p><p>· While developing apps in Java we generally prefer using View Modal concept in which we find each view from our XML layout file inside our Java class and add data to that specific view according to our requirement. In most apps, we use the UI elements to display dynamically so this may sometimes give you an error of Null Reference. In this method, UI elements are declared in XML language whereas the functionality is written in java or Kotlin and we link UI elements with our Java or Kotlin class with the <strong>findViewbyId()</strong> method.</p><p>· If we prefer to use the same language for writing our UI components and for adding the functionality it will help us make it easier to maintain our code. By using this method the number of couplings inside our code will also reduce.</p><p>· Now that a firm base has been formed, lets get started with some fun practical illustrations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DDDAYwI92icmiSA6wi_SPQ.gif" /></figure><h3>How do we get started with Jetpack Compose?</h3><p>· <strong>Installation: </strong>To begin, download the most recent version of <a href="https://developer.android.com/studio">Android Studio Arctic Fox</a>, and create an app using the Empty Compose Activity template. The default template already contains some Compose elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQ_gnc3khjD07F9TQ0b8sA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NSc4tRzJ1mxmvYXgOyNIQ.png" /></figure><p>· <strong>Composable Functions:</strong> Jetpack Compose is built around composable functions. These functions let you define your app’s UI programmatically by describing how it should look and providing data dependencies, rather than focusing on the process of the UI’s construction (initializing an element, attaching it to a parent, etc.). To create a composable function, just add the @Composable annotation to the function name.</p><p>· <strong>Layouts:</strong> UI elements are hierarchical, with elements contained in other elements. In Compose, you build a UI hierarchy by calling composable functions from other composable functions.</p><p>· <strong>Material Design:</strong> Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this lesson, you’ll style your app with material widgets.</p><p>· <strong>Lists and Animations:</strong> Lists and animations are everywhere in apps. In this lesson, you will learn how Compose makes it easy to create lists and fun to add animations.</p><h3>Composable Functions</h3><p>· <strong>Add</strong> <strong>a text element: </strong>First, we’ll display a “Hello world!” text by adding a text element inside the onCreate method. You do this by defining a content block, and calling the Text() function. The setContent block defines the activity&#39;s layout where we call composable functions. Composable functions can only be called from other composable functions. Jetpack Compose uses a Kotlin compiler plugin to transform these composable functions into the app&#39;s UI elements. For example, the Text() function that is defined by the Compose UI library displays a text label on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zt58JTXv-mP5jp-e4D4ZPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*qsqQbqYP84D9YyPjiP1yBw.png" /></figure><p>· <strong>Define a composable function: </strong>To make a function composable, add the @Composable annotation. To try this out, define a MessageCard() function which is passed a name, and uses it to configure the text element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czIgcrmA1T67GDz2Q1e68A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*_xkx7ssO5j7KusK6bWo7vg.png" /></figure><p>· <strong>Preview your Function in Android Studio: </strong><a href="https://developer.android.com/studio">Android Studio</a> lets you preview your composable functions within the IDE, instead of installing the app to an Android device or emulator. The composable function must provide default values for any parameters. For this reason, you can’t preview the MessageCard() function directly. Instead, let’s make a second function named PreviewMessageCard(), which calls MessageCard() with an appropriate parameter. Add the @Preview annotation before @Composable.</p><p>Rebuild your project. The app itself doesn’t change, since the new PreviewMessageCard() function isn&#39;t called anywhere, but Android Studio adds a preview window. This window shows a preview of the UI elements created by composable functions marked with the @Preview annotation. To update the previews at any time, click the refresh button at the top of the preview window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AapSzlMpdtg_P81S8b3MbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDhxynvHzm2zpmyQoe_Uiw.png" /></figure><h3>Layouts</h3><p>· <strong>Add</strong> <strong>Multiple Texts: </strong>So far we’ve built our first composable function and preview! To discover more Jetpack Compose capabilities, we’re going to build a simple messaging screen containing a list of messages that can be expanded with some animations.<br> Let’s start by making our message composable richer by displaying the name of its author and a message content. We need first to change our composable parameter to accept a Message object instead of a String, and add another Text composable inside the MessageCard composable. Make sure to update the preview as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnuIpD5brorya_U_caNMzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*xk8limwxTtSSbqDAbBW6Kw.png" /></figure><p>This code creates two text elements inside the content view. However, since we haven’t provided any information about how to arrange them, the text elements are drawn on top of each other, making the text unreadable.</p><p>· <strong>Using a Column: </strong>The Column function lets you arrange elements vertically. Add Column to the MessageCard() function.<br> You can use Row to arrange items horizontally and Box to stack elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drWG62DKYCpQEmBmf3X2dQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*GjJhCLBbubBtRWcDyHlpNg.png" /></figure><p>· <strong>Add an Image Element: </strong>Let’s enrich our message card by adding a profile picture of the sender. Use the <a href="https://developer.android.com/studio/write/resource-manager#import">Resource Manager</a> to import an image from your photo library or use <a href="https://developer.android.com/images/jetpack/compose-tutorial/profile_picture.png">this one</a>. Add a Row composable to have a well structured design and an Image composable inside it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2xp0vBTK8tLlKHYU9fZZmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*dgcQEwhEpflIZuLmv6zr1w.png" /></figure><p>· <strong>Configure your layout:</strong> Our message layout has the right structure but its elements aren’t well spaced and the image is too big! To decorate or configure a composable, Compose uses <strong>modifiers</strong>. They allow you to change the composable’s size, layout, appearance or add high-level interactions, such as making an element clickable. You can chain them to create richer composables. Let’s use some of them to improve the layout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVlWZuHLI8jp2mKVZNKYfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*5dXVz2ug0EzZNdTZTARXxA.png" /></figure><h3>Material Design</h3><p>· <strong>Use Material Design: </strong>Our message design now has a layout, but it doesn’t look too good yet.</p><p>Jetpack Compose provides an implementation of Material Design and its UI elements out of the box. We’ll improve the appearance of our MessageCard composable using Material Design styling.</p><p>To start, we wrap our MessageCard function with the Material theme created in your project, ComposeTutorialTheme in this case. Do it both in the @Preview and in the setContent function.</p><p>Material Design is built around three pillars: Color, Typography, Shape. Let’s add them one by one.</p><p><strong>Note:</strong> the Empty Compose Activity generates a default theme for your project that allows you to customize MaterialTheme. If you named your project anything different from MyApplication, you can find your custom theme in the ui.theme package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*doDaGzlfpFTBOQSqW9ickg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*opZL6skit6O1Ir81ehFNXw.png" /></figure><p>· <strong>Color:</strong> Styling with colors from the wrapped theme is easy, and you can use values from the theme anywhere a color is needed.</p><p>Let’s style the title and add a border to the image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWFZHByBqKJ8VJgt-V4LjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dv0bFp5x1zkTCVQseqDOuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*LH8Dd1Ms-1vb0O478YF8UQ.png" /></figure><p>· <strong>Typography:</strong> Material Typography styles are available in the MaterialTheme, just add them to the Text composables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWFZHByBqKJ8VJgt-V4LjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dv0bFp5x1zkTCVQseqDOuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*LH8Dd1Ms-1vb0O478YF8UQ.png" /></figure><p>· <strong>Shape:</strong> With Shape we can add the final touches. We also add a padding to the message for a better layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnhvuIgLJ1p1qOO-inv1Sg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*NEqEl4IPUaYSUyq0JDltuw.png" /></figure><p>· <strong>Enable Dark Theme:</strong> <a href="https://developer.android.com/guide/topics/ui/look-and-feel/darktheme">Dark theme</a> (or night mode) can be enabled to avoid a bright display especially at night, or simply to save the device battery. Thanks to the Material Design support, Jetpack Compose can handle the dark theme by default. Having used Material colors, text and backgrounds will automatically adapt to the dark background.</p><p>You can create multiple previews in your file as separate functions, or add multiple annotations to the same function.</p><p>Let’s add a new preview annotation and enable night mode.</p><p>Color choices for the light and dark themes are defined in the IDE-generated Theme.kt file.</p><p>So far, we’ve created a message UI element that displays an image and two texts with different styles and it looks good both in light and dark themes!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F8SxGru3XzElqg%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F8SxGru3XzElqg%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F8SxGru3XzElqg%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/73aca1a3b093488d30030627fca2c4ee/href">https://medium.com/media/73aca1a3b093488d30030627fca2c4ee/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKOmjsH3cJAk71jD192gww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*6Vc4VG1q8Xc2ZH6nGYUbdQ.png" /></figure><h3>Lists and Animations</h3><p>· <strong>Create a List of Messages: </strong>A chat with one message feels a bit lonely, so let’s change our conversation to have more than one message. We need to create a Conversation function that will show multiple messages. For this use case, we can use Compose’s LazyColumn and LazyRow. These composables render only the elements that are visible on screen, so they are designed to be very efficient for long lists. At the same time, they avoid the complexity of RecyclerView with XML layouts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*WPw9ipusLScffbbx-T3mGA.png" /></figure><p>In this code snippet, you can see that LazyColumn has an items child. It takes a List as a parameter and its lambda receives a parameter we’ve named message (we could have named it whatever we want) which is an instance of Message. In short, this lambda is called for each item of the provided List: Import this <a href="https://gist.github.com/yrezgui/26a1060d67bf0ec2a73fa12695166436">sample dataset</a> into your project to help bootstrap the conversation quickly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EoJsGXgBjuiureP-banHOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3lFNO_DNN98o1WIXBBm1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*Ezzx0vMF6D-T-V23UP1RYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*iBSkY0LXoOmgxhgA7_2pDQ.png" /></figure><p>· <strong>Animate Messages while Expanding:</strong> Our conversation is getting more interesting. It’s time to play with animations! We will add the ability to expand a message to show a longer one, animating both the content size and the background color. To store this local UI state, we need to keep track of whether a message has been extended or not. To keep track of this state change, we have to use the functions remember and mutableStateOf.</p><p>Composable functions can store local state in memory by using remember, and track changes to the value passed to mutableStateOf. Composables (and its children) using this state will get redrawn automatically when the value is updated. We call this <a href="https://developer.android.com/jetpack/compose/mental-model#recomposition">recomposition</a>.</p><p>By using Compose’s state APIs like remember and mutableStateOf, any changes to state automatically update the UI:</p><p>Note: you will need to add the following imports to correctly use `by`. Alt+Enter will add them for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQtrk5dJbPzwZD5yCTar2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*meWO0ndVvueWHPKx7Pl1zQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*2JjxjD2qpVQmDSKFgQPing.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*aUy2IabtYiCMH0VB0IPi8g.png" /></figure><p>Now we can change the background of the message content based on isExpanded when we click on a message. We will use the clickable modifier to handle click events on the composable. Instead of just toggling the background color of the Surface, we will animate the background color by gradually modifying its valuefrom MaterialTheme.colors.surface to MaterialTheme.colors.primary and vice versa. To do so, we will use the animateColorAsState function. Lastly, we will use the animateContentSize modifier to animate the message container size smoothly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTerYA144K3Pnyra1feh-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*twT7EeLTmbNlUixABLHw4w.png" /></figure><h3>Conclusion</h3><p>Congratulations, you’ve finished the Compose tutorial! You’ve built a simple chat screen efficiently showing a list of expandable &amp; animated messages containing an image and texts, designed using Material Design principles with a dark theme included and previews — all in <strong>under 100 lines of code! <br></strong>Furthermore, if you have any more doubts you can reach out to me on <a href="http://www.linkedin.com/in/ayush-singh-negi">LinkedIn</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*TlSVfFCXPg3ZotjTJ-HwwA.png" /></figure><p>Here’s what you’ve learned so far:</p><p>· Defining composable functions</p><p>· Adding different elements in your composable</p><p>· Structuring your UI component using layout composables</p><p>· Extending composables by using modifiers</p><p>· Creating an efficient list</p><p>· Keeping track of state and modifying it</p><p>· Adding user interaction on a composable</p><p>· Animating messages while expanding them</p><p>Let’s keep sharpening our Kotlin and Jetpack Compose skills together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e799f262ce50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dscvitpune/getting-started-with-jetpack-compose-e799f262ce50">Getting Started With Jetpack Compose</a> was originally published in <a href="https://medium.com/dscvitpune">Google Developer Students Club Vishwakarma Institute of Technology, Pune</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>