Web http://robotic-controls.com/index.php/ en Using Node.js as a web server http://robotic-controls.com/index.php/learn/programming/using-nodejs-web-server <span>Using Node.js as a web server</span> <div class="field field--name-field-topics field--type-entity-reference field--label-inline"> <div class="field--label">Topics</div> <div class="field--items"> <div class="field--item"><a href="/index.php/topics/web" hreflang="en">Web</a></div> <div class="field--item"><a href="/index.php/topics/html" hreflang="en">HTML</a></div> <div class="field--item"><a href="/index.php/topics/javascript" hreflang="en">JavaScript</a></div> <div class="field--item"><a href="/index.php/topics/gui" hreflang="en">GUI</a></div> </div> </div> <span><span lang="" about="/index.php/users/evan-boldt" typeof="schema:Person" property="schema:name" datatype="">Evan Boldt</span></span> <span>Mon, 08/04/2014 - 18:59</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>Introduction</h3> <p>Node.js is JavaScript that can be run outside of a browser. It is often used to make a fast server for dynamic content.</p> <p>Probably one of the biggest advantages to Node.js, aside from being one of the fastest and easiest to learn server environments, is that JavaScript is the lanugage used on browsers, allowing you to program both the server and client in the same language.</p> <h3>Example</h3> <p>First, download and install node.js</p> <p>Then, start the example by usign the command:</p> <pre>nodejs server.js</pre> <p>This example starts by sending a static HTML form when you visit http://localhost:8080/. It looks like the image below:</p> <p><img src="/sites/default/files/images/Screenshot%20from%202014-08-04%2017%3A44%3A35_0.png" alt="A screenshot of the main page, which is the static form.html file" width="517" height="238" style="display: block; margin-left: auto; margin-right: auto;" class="soft"></p> <p>Clicking the submit button on the form sends a get request to http://localhost:8080/submit. It looks like the image below.</p> <p><img src="/sites/default/files/images/Screenshot%20from%202014-08-04%2017%3A44%3A22_0.png" alt="A screenshot of the dynamically generated response to the form." width="558" height="236" style="display: block; margin-left: auto; margin-right: auto;" class="soft"></p> <p>The interesting part of this script is the <strong>(url_parts.pathname == '/submit')</strong> condition. This is where the dynamic page generation happens. It starts by just regurgitating the information it was sent in the form. Note that the variable names of the <strong>url_parts.query.varname</strong> match up to the "name" attribute in each of the form elements. One of the most powerful features of node.js is that the program remains running between requests, unlike PHP. As a result, we can store variables which can retain their values as long as the process stays running. Storing any really important information this way is a bad idea, since a crash or shutdown would cause the data to disappear. A database can be used, such as MySQL. However, probably the most popular database for node.js servers is MongoDB, which uses JSON encoded data.</p> <p>This form would also work by POST, if the form method were changed from GET to POST.</p> <pre>var http = require('http'); // these lines are somewhat similar to #include in C++ var util = require('util'); // except that the left hand side is an object/variable var url = require('url'); var fs = require('fs'); // provide a "database" messages = [] var server = http.createServer(function (req,res){ // parse the URL var url_parts = url.parse(req.url,true); // functions to serve static files function sendHTML(filepath) { // read the file asyncronously fs.readFile(filepath,function(error,contents){ // once the file is loaded, this function runs console.log('Serving the html ' + filepath); res.end(contents); // end the request and send the file }); } function sendCSS(filepath) { // once the file is loaded, this function runs fs.readFile(filepath,function(error,contents){ console.log('Serving the css ' + filepath); res.end(contents); // end the request and send the file }); } // serve the index page from a static file if( url_parts.pathname == '/' ) { sendHTML('./form.html'); } // serve the CSS page from a static file else if ( url_parts.pathname == '/style.css') { sendCSS('./style.css') } // generate a dynamic page else if ( url_parts.pathname == '/submit' ) { var html = '&lt;html&gt;&lt;body&gt;'; // begin the minimal html structure html += "&lt;h2&gt;Query received&lt;/h2&gt;"; html += "Name: " + url_parts.query.name; html += '&lt;br /&gt;'; html += "Email: " + url_parts.query.email; html += '&lt;br /&gt;'; html += "Message: " + url_parts.query.message; html += '&lt;br /&gt;'; html += '&lt;h2&gt;Previous Messages&lt;/h2&gt;'; messages.push(url_parts.query.message) // loop through the old messages for(m in messages) { html += messages[m]; html += '&lt;br /&gt;'; } html += '&lt;/body&gt;&lt;/html&gt;'; // end the minimal html structure res.end(html); // end the request and send the response HTML } // if the url was not recognized, 404 else { res.writeHead(404) // put a header for not found<br> // print the page and end the request res.end("&lt;h1&gt;404 - Path not recognized&lt;/h1&gt;"); } }); server.listen(8080); util.log('Server listenning at localhost:8080');</pre></div> <div class="field field--name-field-attachments field--type-file field--label-inline"> <div class="field--label">Attachments</div> <div class="field--items"> <div class="field--item"><span class="file file--mime-application-zip file--package-x-generic icon-before"><span class="file-icon"><span class="icon glyphicon glyphicon-compressed text-primary" aria-hidden="true"></span></span><span class="file-link"><a href="http://robotic-controls.com/sites/default/files/learn/nodejsExample_0.zip" type="application/zip; length=1757" title="Open archive in new window" target="_blank" data-toggle="tooltip" data-placement="bottom">nodejsExample.zip</a></span><span class="file-size">1.72 KB</span></span></div> </div> </div> <div class="field field--name-field-disqus field--type-disqus-comment field--label-above"> <div class="field--label">Disqus</div> <div class="field--item"><drupal-render-placeholder callback="Drupal\disqus\Element\Disqus::displayDisqusComments" arguments="0=Using%20Node.js%20as%20a%20web%20server&amp;1=http%3A//robotic-controls.com/index.php/learn/programming/using-nodejs-web-server&amp;2=node/97" token="KQxPGYjBeA5yv_nM6avDgCU40aiVc30gpjaABollOVU"></drupal-render-placeholder></div> </div> Mon, 04 Aug 2014 23:59:45 +0000 Evan Boldt 97 at http://robotic-controls.com JavaScript and jQuery Introduction http://robotic-controls.com/index.php/learn/programming-concepts/javascript-and-jquery-introduction <span>JavaScript and jQuery Introduction</span> <div class="field field--name-field-topics field--type-entity-reference field--label-inline"> <div class="field--label">Topics</div> <div class="field--items"> <div class="field--item"><a href="/index.php/topics/introduction" hreflang="en">Introduction</a></div> <div class="field--item"><a href="/index.php/topics/programming" hreflang="en">Programming</a></div> <div class="field--item"><a href="/index.php/topics/web" hreflang="en">Web</a></div> </div> </div> <span><span lang="" about="/index.php/users/evan-boldt" typeof="schema:Person" property="schema:name" datatype="">Evan Boldt</span></span> <span>Tue, 03/26/2013 - 00:29</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>Introduction</h3> <p>JavaScript is an actual programming language that is interpreted and run by your browser. It makes a webpage interactive and dynamic instead of just a rigid page that doesn't change once it's loaded. You can use it to send and recieve bits of information without having to load another page.&nbsp;&nbsp;It allows you to drag and drop elements, or react to clicks and hovers.&nbsp;You can even use it to make an in-browser game.</p> <p>It is syntactically similar to Java. It requires semi-colons at the end of each statement. However, it does not have rigid data types. Any variable can store data of any type - sort of like python. In fact, a variable can even store a function or actually contain nothing (undefined).<!--break--></p> <h3>jQuery</h3> <p>Many of the ways you would routinely use JavaScript are made drastically easier by using the jQuery library. jQuery provides a simplified interface for finding elements in a webpage, easy methods for modifying styles and appending content, simple functions for doing making fluid transition animations, and a reliable way to send and recieve data like JSON to a server asyncronously.</p> <h4>Setting Up jQuery</h4> <p>the jQuery .js file simply needs to be included in the pages scripts. This can be done really easily by using Google's hosted libraries. One of the advanatages to using Google's hosted libraries is that the file may already be cached in the user's browser.</p> <pre>&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt;</pre> <h4>Using the JavaScript Console</h4> <p>The JavaScript console is extremely useful. In Chrome, it can be revealed by going to Options &gt; Tools &gt; Developer Tools &gt; Console (the furthest tab to the right). This provides an interactive console. You can type a line of JavaScript, and you can read any errors or the output of any console.log() command in the JavaScript ran up until this point.</p> <h3>Searching for Elements</h3> <p>Elements in a webpage can be searched for extremely easily with jQuery. The the string used in the search is practically identical to the specifiers in CSS. ID's are specified with a <strong>#</strong> sign, classes are preceeded by a <strong>.</strong>, you can search for a specific drilldown by seperating specifiers by spaces, and seperate searches can be done simulteneously be using a comma.</p> <pre>results = $("#main .gallery img"); // gets img tags in gallery classes in main ID</pre> <h3>Modifying Elements</h3> <h4>Contents</h4> <p>To <em>replace</em> the contents of an element, you can use either the html or text method, where text will strip tags. Both the html and text methods can return the current contents of an element if the function is called without any parameters.</p> <pre>var titleText = $("#main h2.title").text() //gets the text in the heading tag<br>$("#main h2.title").text("New Title!"); //replaces the text in the heading tag</pre> <p>To <em>add</em> to the current contents at the end. Note that there is also a prepend method that adds to the beginning.</p> <pre>$("#main").append('&lt;div class="new"&gt;New Stuff&lt;/div&gt;');</pre> <h4>Styles</h4> <p><a href="http://api.jquery.com/category/manipulation/style-properties/">Style information</a> can be set and retrieved similar to the contents of an element. Select the element then use the <a href="http://api.jquery.com/css/">css jQuery method</a> to either retrieve or set the style by calling <strong>.css()</strong> with only the attribute or by calling it with both the attribute name and a value. It can also be called with a dictionary as an argument, with key value pairs corresponding to the css attribute names and values.</p> <pre>$("#comments .new").css("color", "#C00"); //adds to elements' style="" attribute</pre> <p>Another way to change the style of an element would be to simply toggle a class on the element, then defining the CSS in a stylesheet. jQuery provides a lot of methods for this, like checking whether an element has a class (hasClass), adding a class (addClass), switching back and forth whether an element has a class (toggleClass), and removing a class (removeClass).</p> <p>Other style information can be easily retrieved and set in jQuery, like heights, widths, margins, positions on page, and scoll positions.</p> <h4>Animation</h4> <p>Styling can be easily animated with jQuery <a href="http://api.jquery.com/category/effects/">effects</a>, which is possibly one of its most useful features.</p> <p>Some animations are predefined all having to do with hiding and revealing elements, like: hide(), .slideDown(), slideUp(), fadeIn, fadeOut</p> <pre>$(".oops").hide()</pre> <p>Alternately, an animation can be completely customized with very little code by using the <a href="http://api.jquery.com/animate/">animate</a> method. Many css values can be animated except colors, which requires jQuery UI. The first argument to animate is a dictionary of attributes and values for the styles, and the second argument is the duration of the animation in milliseconds.</p> <pre>$("#main").animate({ width: "50%" }, 1000 );</pre> <h3>Events</h3> <p>Events are what make JavaScript truly interactive. They allow your script to react to changes.</p> <p>Essentially, events are simply functions that are called whenever something happens. For example, if you want to make a webpage do something in response to a click, you simply say attach a function to an elements click event.</p> <pre>function reactionToEvent() {<br> $(this).text("CHANGED!"); //change calling elements text<br>}<br><br>$("#mybutton").click(reactionToEvent);</pre> <p>Which is the same thing as:</p> <pre>$("#mybutton").click(function() {<br> $(this).text("CHANGED!"); //change calling elements text<br>});</pre> <p>There are all kinds of events available. One of the most common ones used in jQuery is to delay actions until the document is loaded by using:&nbsp;$(document).ready(handler)</p> <p>Here are some of the other most common ones:<br><strong>click</strong>, <strong>mousedown</strong>, <strong>mouseup</strong> - React to button presses<br><strong>hover</strong> - Reacts to the mouse entering or leaving an element<br><strong>keydown</strong>,&nbsp;<strong>keypress</strong> - Reacts to keyboard button presses like hotkeys.<br><strong>change</strong> - Reacts to form elements being altered like inputs, select boxes, and radio buttons</p> <p>There are many more events available than that, but they may require the use of the jQuery bind method.</p> <h3>Sending and Receiving JSON</h3> <p>JSON is an awesome tool for sending structured data to and from a server. You can retain the data types of any JavaScript variable, like a dictionary that has arrays that have all kinds of different data types. It turns the data types into a structured and linear string, which is a process called serializing. For example, a CSV is a sort of a way of serializing a two dimensional array.</p> <pre>var stuff = {<br> numbers: [0,1,3,6],<br> on: True,<br> comment: "Hello"<br>};<br><br>function successResponse(responseData) {<br> console.log(responseData); // dumps the data to browser's console<br>}<br>function failResponse() {<br> console.log("There was an error");<br>}<br><br>// send the stuff in JSON by POST to localhost and run the above function when done<br>$.ajax({ type: "POST", url: 'localhost', dataType: 'json', data: stuff, success: successResponse }).fail(failResponse);</pre></div> <section> </section> <div class="field field--name-field-disqus field--type-disqus-comment field--label-above"> <div class="field--label">Disqus</div> <div class="field--item"><drupal-render-placeholder callback="Drupal\disqus\Element\Disqus::displayDisqusComments" arguments="0=JavaScript%20and%20jQuery%20Introduction&amp;1=http%3A//robotic-controls.com/index.php/learn/programming-concepts/javascript-and-jquery-introduction&amp;2=node/43" token="llxfFY1hrKiqDtfgOrvk11pf7SfH95BVnRswU74bjzM"></drupal-render-placeholder></div> </div> Tue, 26 Mar 2013 05:29:51 +0000 Evan Boldt 43 at http://robotic-controls.com http://robotic-controls.com/index.php/learn/programming-concepts/javascript-and-jquery-introduction#comments CSS Introduction http://robotic-controls.com/index.php/learn/programming-concepts/css-introduction <span>CSS Introduction</span> <div class="field field--name-field-topics field--type-entity-reference field--label-inline"> <div class="field--label">Topics</div> <div class="field--items"> <div class="field--item"><a href="/index.php/topics/web" hreflang="en">Web</a></div> <div class="field--item"><a href="/index.php/topics/programming" hreflang="en">Programming</a></div> <div class="field--item"><a href="/index.php/topics/gui" hreflang="en">GUI</a></div> <div class="field--item"><a href="/index.php/topics/introduction" hreflang="en">Introduction</a></div> </div> </div> <span><span lang="" about="/index.php/users/evan-boldt" typeof="schema:Person" property="schema:name" datatype="">Evan Boldt</span></span> <span>Sat, 03/23/2013 - 21:56</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>Introduction</h3> <pre class="float-right lang-html" style="clear: right;">htmlTagName, #idname, .classname {<br /> stylename: stylevalue;<br /> color: black;<br /> font-size: 12px;<br /> background-color: #ddd;<br />}</pre> <p>CSS stands for Cascading Style Sheet. In HTML, you use it to apply a certain look to specific elements in the page. CSS makes it easy to give every page on your website a unified appearance. The format is extremely straightforward, but to be effective you need to know how to specify which element you want styled, find current styling information in a webpage, and you must be aware of all of the styles that can be applied to an element. The general form of a style in a CSS file is like the example shown to the right.</p> <!--break--> <h3>Specifiers</h3> <p>Specifiers tell the browser which elements to apply the style to.</p> <ul><li>tags like <strong>&lt;body&gt;</strong>, <strong>&lt;p&gt;</strong>, <strong>&lt;div&gt;</strong>, and <strong>&lt;span&gt;</strong> are specified with just the text</li> <li>an ID in html is declared in the element like <strong>&lt;div id="rightSidebar"&gt;</strong>, and specified in CSS like <strong>#rightSidebar</strong></li> <li>a class in html is declared in the element like <strong>&lt;div class="gallery"&gt;</strong>, and specified in CSS like <strong>.gallery</strong></li> </ul><p>Specifiers may be chained in special ways to select more elements or narrow in on an element</p> <ul><li>Multiple specifiers can use the same style by seperating the specifiers with comments</li> <ul><li><strong>#sidebar, .gallery {...}</strong> applies the style within the brackets to both the sidebar ID and gallery class.</li> </ul><li>You can drill down to an class by seperating specifiers with a space</li> <ul><li><strong>#sidebar h3 {...}</strong> applies the style within the brackets to only h3 elements within the sidebar element</li> </ul></ul><h3>Styling</h3> <h4>Color</h4> <p>There are several ways to pick a color. The numerical methods all are in the order of "red, green, blue", with low numbers being darker and higher numbers being lighter.</p> <table border="0"><caption>CSS Color Examples</caption> <thead><tr><th>Name</th><th>3 digit hex</th><th>6 digit hex</th><th>RGB</th><th>RGB+Alpha Transparency</th></tr></thead><tbody><tr><td>black</td> <td>#000</td> <td>#000000</td> <td>rgb(0,0,0)</td> <td>rgba(0,0,0,1.0)</td> </tr><tr><td>white</td> <td>#FFF</td> <td>#FFFFFF</td> <td>rgb(255,255,255)</td> <td>rgba(255,255,255,1.0)</td> </tr><tr><td>red</td> <td>#F00</td> <td>#FF0000</td> <td>rgb(255,0,0)</td> <td>rgba(255,0,0,1.0)</td> </tr><tr><td>green</td> <td>#0F0</td> <td>#00FF00</td> <td>rgb(0,255,0)</td> <td>rgba(255,0,0,1.0)</td> </tr><tr><td>blue</td> <td>#00F</td> <td>#0000FF</td> <td>rgb(0,0,255)</td> <td>rgba(0,0,0,1.0)</td> </tr><tr><td>grey</td> <td>innaccurate</td> <td>#808080</td> <td>rgb(129,129,129)</td> <td>rgba(129,129,129,1.0)</td> </tr><tr><td>transparent</td> <td>N/P</td> <td>N/P</td> <td>N/P</td> <td>rgba(0,0,0,0)</td> </tr><tr><td>N/P</td> <td>N/P</td> <td>N/P</td> <td>N/P</td> <td>rgba(0,0,0,0.5)</td> </tr></tbody></table><h4>Styles List</h4> <p>Here are some sample styles applied to a div tag with the text "demo" inside of it.</p> <style> <!--/*--><![CDATA[/* ><!--*/ #cssDemo .cssDemoLine { border: 1px solid #ccc; padding: 2px 8px; margin: 2px 6px; } /*--><!]]>*/ </style><table id="cssDemo"><thead><tr><th>Style Name</th><th>Description</th><th>Sample Usage</th><th>Sample Result</th></tr></thead><tbody><tr><td>color</td> <td>The color of the <em>font</em></td> <td>color: #090;</td> <td> <div class="cssDemoLine" style="color: #090;">DEMO TEXT</div> </td> </tr><tr><td>font-size</td> <td>The size of the font, usually in px or em</td> <td>font-size: 14px;</td> <td> <div class="cssDemoLine" style="font-size: 14px;">DEMO TEXT</div> </td> </tr><tr><td>font-style</td> <td>Italicizes text</td> <td>font-style: italics;</td> <td> <div class="cssDemoLine" style="font-style: italics;">DEMO TEXT</div> </td> </tr><tr><td>font-weight</td> <td>Controls the "boldness" of text</td> <td>font-weight: bold;</td> <td> <div class="cssDemoLine" style="font-weight: bold;">DEMO TEXT</div> </td> </tr><tr><td>text-decoration</td> <td>Underline, or overline, and strikethrough to text</td> <td>text-decoration: <br />underline;</td> <td> <div class="cssDemoLine" style="text-decoration: underline;">DEMO TEXT</div> </td> </tr><tr><td>text-align</td> <td>The horizontal positioning of text</td> <td>text-align: center;</td> <td> <div class="cssDemoLine" style="text-align: center;">DEMO TEXT</div> </td> </tr><tr><td>vertical-align</td> <td>The vertical positioning of text</td> <td>vertical-align: middle;</td> <td> <div class="cssDemoLine" style="vertical-align: middle;">DEMO TEXT</div> </td> </tr><tr><td>font-family</td> <td>Name of font. Use web-safe fonts!</td> <td>font-family: Serif;</td> <td> <div class="cssDemoLine" style="font-family: Serif;">DEMO TEXT</div> </td> </tr><tr><td>line-height</td> <td>Spaces text lines. 2em is 'double spaced'</td> <td>line-height: 2em;</td> <td> <div class="cssDemoLine" style="line-height: 2em;">DEMO TEXT</div> </td> </tr><tr><td>height<br />width</td> <td>Controls the height/width of block elements</td> <td>width: 40px;</td> <td> <div class="cssDemoLine" style="width: 40px;">DEMO TEXT</div> </td> </tr><tr><td>background-color</td> <td>The background color of the box</td> <td>background-color: #fff;</td> <td> <div class="cssDemoLine" style="background-color: #fff;">DEMO TEXT</div> </td> </tr><tr><td>background</td> <td>Takes all background related styles<br />Can do color, image, image position, repeats</td> <td>background: #fff<br />url() no-repeat<br />right 50%;</td> <td> <div class="cssDemoLine" style="background: #fff url('/themes/jne/images/edit-find-symbolic.png') no-repeat right 50%;">DEMO TEXT</div> </td> </tr><tr><td>border</td> <td>A line around the box</td> <td>border: 1px solid #090;</td> <td> <div class="cssDemoLine" style="border: 1px solid #090;">DEMO TEXT</div> </td> </tr><tr><td>border-radius</td> <td>Rounds the edges of the box</td> <td>border-radius: 8px;</td> <td> <div class="cssDemoLine" style="border-radius: 8px;">DEMO TEXT</div> </td> </tr><tr><td>margin</td> <td>Adds spacing to the <em>outside</em> of the box</td> <td>margin: 5px;</td> <td> <div class="cssDemoLine" style="margin: 5px;">DEMO TEXT</div> </td> </tr><tr><td>padding</td> <td>Adds spacing to the <em>inside</em> of the box</td> <td>padding: 5px;</td> <td> <div class="cssDemoLine" style="padding: 5px;">DEMO TEXT</div> </td> </tr><tr><td>float</td> <td>Pushes to side and surroundings wrap around it</td> <td>float: right;</td> <td> <div class="cssDemoLine" style="float: right;">DEMO TEXT</div> </td> </tr><tr><td>display</td> <td><strong>inline</strong>: on same line as text like a span or img<br /><strong>block</strong>: use width and obey margins like div<br /><strong>inline-block</strong>: inline but can width and margin<br /><strong>none</strong>: not shown at all</td> <td>display:inline;</td> <td> <div class="cssDemoLine" style="display: inline;">DEMO TEXT</div> </td> </tr><tr><td>position</td> <td><strong>static</strong>: the normal way of position<br /><strong>absolute</strong>: put at coordinates on screen<br /><strong>relative</strong>: like absolute, but zero'd at static<br /><strong>fixed</strong>: like absolute, but moves with scrolls<br /><em>note: nonstatic needs top, left, right, or bottom</em></td> <td>position: relative;<br />left: 10px;</td> <td> <div class="cssDemoLine" style="position: relative; left: 10px;">DEMO TEXT</div> </td> </tr><tr><td>z-index</td> <td>Larger values are higher when overlapping</td> <td>z-index: 10;</td> <td> </td> </tr><tr><td>text-shadow</td> <td>adds a drop shadow to text. multiples by comma<br />text-shadow: right down size color</td> <td>text-shadow: <br />-1px 0 0 #fff;</td> <td> <div class="cssDemoLine" style="text-shadow: -1px 0 0 #fff;">DEMO TEXT</div> </td> </tr><tr><td>box-shadow</td> <td>Adds drop shadow to the box.<br />Similar parameters to text-shadow<br />Shadows can be inset (inside the box).</td> <td>box-shadow:<br />inset 0 0 2px #fff,<br />0 0 4px #000;</td> <td> <div class="cssDemoLine" style="box-shadow: inset 0 0 2px #fff, 0 0 4px #000;">DEMO TEXT</div> </td> </tr></tbody></table><h4>Other Style Information</h4> <p>As a general rule, you can use a shorthand to differentiate the different directions of a style either in the order or top, right, bottom, left or in the order top+bottom and left+right. It follows a clockwise rule, and saves a lot of typing particularly on the margin and padding styles. For example:</p> <table border="0"><caption>Direction Notations</caption> <thead><tr><th>Seperated</th><th>4 direction shorthand</th><th>2 direction Shorthand</th></tr></thead><tbody><tr><td> <pre>padding-top: 8px;<br />padding-right: 5px;<br />padding-bottom: 8px;<br />padding-left: 5px;</pre> </td> <td> <pre>padding: 8px 5px 8px 5px;</pre> </td> <td> <pre>padding: 8px 5px;</pre> </td> </tr></tbody></table><p>Gradients can be made with <a href="http://www.colorzilla.com/gradient-editor/">this</a> very simple generator.</p> <p>The safe choices for fonts are really limited. With modern browsers, you can attach font files to pages. This process is made extremely easy with the <a href="http://www.google.com/webfonts">Google Web Font API</a>.</p> <h3>Development</h3> <p>As a general rule, you will want to have a local instance of the website you are developing for. If not, you can always test the css in-browser in chrome easily through menu &gt; tools &gt; developer tools. The magnifying glass in the bottom left will let you select an element visually on the screen. Then, the information on what styles are active and overridden is in the right column, and the tag's place in html is shown in the left. You can actually double click on just about anything in there and modify the contents of the page or the style information.</p></div> <section> </section> <div class="field field--name-field-disqus field--type-disqus-comment field--label-above"> <div class="field--label">Disqus</div> <div class="field--item"><drupal-render-placeholder callback="Drupal\disqus\Element\Disqus::displayDisqusComments" arguments="0=CSS%20Introduction&amp;1=http%3A//robotic-controls.com/index.php/learn/programming-concepts/css-introduction&amp;2=node/42" token="z7dk7Sd6jOZFayBewjycHjdX9ziipTn4SJn2WNeJk-o"></drupal-render-placeholder></div> </div> Sun, 24 Mar 2013 02:56:09 +0000 Evan Boldt 42 at http://robotic-controls.com http://robotic-controls.com/index.php/learn/programming-concepts/css-introduction#comments 3D SVG Graph http://robotic-controls.com/index.php/learn/python-guis/3d-svg-graph <span>3D SVG Graph</span> <div class="field field--name-field-topics field--type-entity-reference field--label-inline"> <div class="field--label">Topics</div> <div class="field--items"> <div class="field--item"><a href="/index.php/topics/programming" hreflang="en">Programming</a></div> <div class="field--item"><a href="/index.php/topics/web" hreflang="en">Web</a></div> <div class="field--item"><a href="/index.php/topics/gui" hreflang="en">GUI</a></div> </div> </div> <span><span lang="" about="/index.php/users/evan-boldt" typeof="schema:Person" property="schema:name" datatype="">Evan Boldt</span></span> <span>Fri, 03/15/2013 - 20:19</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>Introduction</h3> <p>An SVG is a type of graphic that is defined by shapes and math instead of discrete pixels. So, it is scales nicely, but can't make photo-realistic images. An (currently) SVG is two dimensional. That does not mean, though, that we cannot represent 3D information in this 2D space. After all, it is shown in 2D anyway. To accomplish this, we will build our own 3D <a href="http://en.wikipedia.org/wiki/Rotation_matrix">rotation matrices</a>, and a 3D to 2D <a href="http://en.wikipedia.org/wiki/3D_projection">projection matrix</a>. The 3D points can be multiplied by both of these matrices to make it appear 3D, albeit somewhat flat due to the orthographic projection.</p> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script><script src="http://robotic-controls.com/sites/default/files/learn/3dgraph.js.txt"></script><h4>Interactive Graph Demo</h4> <p>This SVG grapher was made so that a user easily visualize and control the end manipulator of a robotic arm in 3D through a web browser. It may be viewed on <a href="http://www.niu.edu/CEET/NotDaVinci">this page</a> on the NIU College of Engineering and Engeering Technology website, but the arm is usually left off for safety.</p> <div style="text-align: center;"><svg height="320" id="3d-graph" style="height: 320px; width:342px; margin: 0 auto; padding: 5px; background: #eee; border-radius: 5px; border: 1px solid #777; cursor:move;" version="1.1" width="352" xmlns="http://www.w3.org/2000/svg"><!-- neg axis --><line id="neg-axis-x" style="stroke:rgba(250,200,200,0.5);stroke-width:2" x1="100" x2="400" y1="250" y2="250"></line><line id="neg-axis-y" style="stroke:rgba(200,250,200,0.5);stroke-width:2" x1="100" x2="100" y1="250" y2="0"></line><line id="neg-axis-z" style="stroke:rgba(200,200,250,0.5);stroke-width:2" x1="100" x2="0" y1="250" y2="400"></line><!-- axis --><line id="axis-x" style="stroke:rgb(200,0,0);stroke-width:2" x1="100" x2="400" y1="250" y2="250"></line><line id="axis-y" style="stroke:rgb(0,200,0);stroke-width:2" x1="100" x2="100" y1="250" y2="0"></line><line id="axis-z" style="stroke:rgb(0,0,200);stroke-width:2" x1="100" x2="0" y1="250" y2="400"></line></svg><br /> Hold left click and drag to move point.<br /> Hold middle click and drag to rotate.</div> <h3>Usage</h3> <p>Although the implementation starts to get somewhat complicated, the usage is actually somewhat straightforward. Get the <a href="http://robotic-controls.com/sites/default/files/learn/3dgraph.js.txt">attached javascript</a> file, and make an <a href="http://robotic-controls.com/learn/programming-concepts/html-introduction">html</a> file that contains this:</p> <pre> &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="3dgraph.js"&gt;&lt;/script&gt; &lt;svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="320" width="352" id="3d-graph" style="height: 320px; width:342px; margin: 0 auto; padding: 5px;" &gt; &lt;!-- neg axis --&gt; &lt;line x1="100" y1="250" x2="400" y2="250" id="neg-axis-x" style="stroke:rgba(250,200,200,0.5);stroke-width:2"/&gt; &lt;line x1="100" y1="250" x2="100" y2="0" id="neg-axis-y" style="stroke:rgba(200,250,200,0.5);stroke-width:2"/&gt; &lt;line x1="100" y1="250" x2="0" y2="400" id="neg-axis-z" style="stroke:rgba(200,200,250,0.5);stroke-width:2"/&gt; &lt;!-- axis --&gt; &lt;line x1="100" y1="250" x2="400" y2="250" id="axis-x" style="stroke:rgb(200,0,0);stroke-width:2"/&gt; &lt;line x1="100" y1="250" x2="100" y2="0" id="axis-y" style="stroke:rgb(0,200,0);stroke-width:2"/&gt; &lt;line x1="100" y1="250" x2="0" y2="400" id="axis-z" style="stroke:rgb(0,0,200);stroke-width:2"/&gt; &lt;/svg&gt; </pre> <h4>Interfacing</h4> <p>The coordinates of the point above are stored in the variables <code>tx</code>, <code>ty</code>, and <code>tz</code>. If you just wish to read it, just read the variables. If you modify them, you have to update the display with <code>mainDot.changePoint()</code></p> <p>A point is simply a vector. A dot is the point plus the graphical representation. A line is two points and a graphical connection between them.</p> <h3>How it Works</h3> <p>This implementation uses the jQuery library, which is much less useful than usual since jQuery can only create HTML DOM objects and not SVG DOM objects as required in this usage. It is still useful for it's event bindings and some search features.</p> <p>There is a point class with an x, y, and z. Points are used to in the graphical classes Dot and Line, where line has two points for a start and an end. Points are multiplied by rotation and projection matrices to turn their 3 dimensions into 2 dimensions. The rotation matrix angles are modified by mouse movement during a click event. When the rotation matrix is changed, the points must be multiplied with the new matrix and the result must be updated on the SVG.</p> <p>In this specific usage, there were 7 points used for the axes. A zero point and points at the maximum and minimum (positive and negative) for each direction. There is a dot at the point you want to visualize in the 3D space, as well as 3 guide lines to help with perspective. The guide lines are entirely necessary. It would also be possible to plot a curved line by using many Line classes or even making your own class that uses the SVG path tag to generate a smooth curve. Another possible feature might be to put a Dot class at a point on the lone closest to the mouse and showing the x,y, and z coordinates.</p> </div> <section> </section> <div class="field field--name-field-disqus field--type-disqus-comment field--label-above"> <div class="field--label">Disqus</div> <div class="field--item"><drupal-render-placeholder callback="Drupal\disqus\Element\Disqus::displayDisqusComments" arguments="0=3D%20SVG%20Graph&amp;1=http%3A//robotic-controls.com/index.php/learn/python-guis/3d-svg-graph&amp;2=node/39" token="Oyh1qWqtZmY38YB45OWOCZtatFGoOxNEIcx9cZBbnFo"></drupal-render-placeholder></div> </div> Sat, 16 Mar 2013 01:19:09 +0000 Evan Boldt 39 at http://robotic-controls.com http://robotic-controls.com/index.php/learn/python-guis/3d-svg-graph#comments HTML Introduction http://robotic-controls.com/index.php/learn/programming-concepts/html-introduction <span>HTML Introduction</span> <div class="field field--name-field-topics field--type-entity-reference field--label-inline"> <div class="field--label">Topics</div> <div class="field--items"> <div class="field--item"><a href="/index.php/topics/web" hreflang="en">Web</a></div> <div class="field--item"><a href="/index.php/topics/programming" hreflang="en">Programming</a></div> <div class="field--item"><a href="/index.php/topics/gui" hreflang="en">GUI</a></div> <div class="field--item"><a href="/index.php/topics/introduction" hreflang="en">Introduction</a></div> </div> </div> <span><span lang="" about="/index.php/users/evan-boldt" typeof="schema:Person" property="schema:name" datatype="">Evan Boldt</span></span> <span>Thu, 02/28/2013 - 10:54</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>Introduction</h3> <p><a href="http://en.wikipedia.org/wiki/HTML">HTML</a> is the language that your browser reads when it shows you a webpage. It is a variant of XML. &nbsp;It makes the actual content that you see, but also can contain visual styling information (typically in the form of an external CSS file) and also can have an in-browser (client-side) programming language called JavaScript.</p> <div style="float: right; margin: 0 0 0 9px;"> <h4>Bare Minimum Example</h4> <pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt; &nbsp; &lt;head&gt; &nbsp; &lt;title&gt;Minimal&lt;/title&gt; &nbsp; &lt;/head&gt;<br> &lt;body&gt;<br>&nbsp; &nbsp; &lt;p&gt;Hello World!&lt;/p&gt;<br>&nbsp; &lt;/body&gt;<br>&lt;/html&gt;</pre> </div> <h4>Tag Structure</h4> <p>Tags are put on either end of something to describe the content between the tags. Since HTML is visual, think of a tag as a box drawn around whatever is inside of it. The outermost tags are &lt;HTML&gt;, &lt;HEAD&gt;, and &lt;BODY&gt;. The &lt;HTML&gt; tag simply says that the contents are HTML. It is the very outermost box on the screen. The &lt;HEAD&gt; tag is invisible. It summarizes the contents (like title and keywords) and also lists files the page needs like stylesheets and scripts - both of which can alternatively be embedded into the actual HTML file if desired instead of being a seperate file. The &lt;BODY&gt; tag is where the actual content that you see on in the browser window goes. It can contain images, text, and other containers.<!--break--></p> <h3>Basic Tags</h3> <h4>&lt;p&gt; - Paragraph</h4> <p>Paragraph tags are useful for providing that spatial seperation between paragraphs. To make a new line, use the self-closing &lt;br /&gt; tag. However, a paragraph is not a line break. the distance between the paragraphs is often a ratio of the line height, like 0.5 lines or 1.5 lines. In print, paragraphs also are indented - a style that can be modified with the text-indent CSS property. So, separating paragraphs by using a separate set of tags more flexible than using some number of line breaks.</p> <h4>&lt;img /&gt; - Image</h4> <p>&nbsp;The image tag is self-closing, which is why it requires the trailing slash. The URL of the image goes in the "href" attribute, and the alternative text if the image cannot be loaded goes in the "alt" attribute.</p> <pre>&lt;img src="http://imgs.xkcd.com/comics/interblag.png" height="432" width="400"<br> alt="An XKCD comic about blog names" /&gt;</pre> <h4>&lt;strong&gt; - Bold</h4> <p>The strong tag makes text bold. Also, the &lt;b&gt; tag can be used, but it is considered outdated for some reason. Example:</p> <pre>&lt;p&gt; ... to &lt;strong&gt;boldly&lt;/strong&gt; go where no man has gone before!&lt;/p&gt;</pre> <h4>&lt;em&gt; - Italics</h4> <p>The emphasis tag makes text italicized. The &lt;i&gt; tag can be used to make italics, but is also weirldy obsolete. Example:</p> <pre>&lt;p&gt;&lt;em&gt;Emphasize&lt;/em&gt; makes italics for some reason&lt;/p&gt;</pre> <h3>Lists</h3> <p>Lists are occasionally used in the body of text for readability, but in websites they are more commonly used for hierarchical (multi-level) navigation. As a general rule, lists should be incomplete sentences and not end with a period. At the very least, the sentence completeness should be consistent throughout the list.</p> <h4>&lt;li&gt; - List item</h4> <p>To make a single list element, wrap some text with &lt;li&gt; tags. This element must be within a list container. The type of container will decide whether there should be bullet points or numbers in front of the list item.</p> <h4>&lt;ul&gt; - Unordered list container</h4> <p>An unordered list element contains list items that have no particular order. This is the most common type of list. The default style applies a different kind of bullet point for each tier of the unordered list.</p> <h4>&lt;ol&gt; - Ordered list container</h4> <p>An ordered list element contains list items that must be in a particular order. it is primarily used for procedural lists that describe a chronological process (a step by step) or it can be used for rankings (a top 10).</p> <p>The starting number can be chosen by the start attribute ex: &lt;ol start="10"&gt;</p> <div style="float: right; margin: 0 0 0 16px;"> <h4>Example Result</h4> <ol> <li>Follow This Tutorial <ul> <li>Discover that it is easy</li> <li>Tell your friends</li> </ul> </li> <li>???</li> <li>Profit</li> </ol></div> <h4>Example Code</h4> <pre>&lt;ol&gt;<br>&lt;li&gt;Follow Tutorial<br> &lt;ul&gt;<br> &lt;li&gt;Discover it is easy&lt;/li&gt;<br> &lt;li&gt;Tell friends&lt;/li&gt;<br> &lt;/ul&gt;<br>&lt;/li&gt;<br>&lt;li&gt;???&lt;/li&gt;<br>&lt;li&gt;Profit&lt;/li&gt;<br>&lt;/ol&gt;</pre> <h3>Tables</h3> <p>The easiest way to learn to make a table is by example, but first here is a quick description of all the table related tags:</p> <ul> <li>&lt;table&gt; - the container for the whole table</li> <li>&lt;thead&gt; - the top area of the table (for categories)</li> <li>&lt;th&gt; - a table heading cell</li> <li>&lt;tbody&gt; - the main area</li> <li>&lt;tr&gt; - a table row</li> <li>&lt;td&gt; - a table cell</li> <li>&lt;tfoot&gt; - the bottom area (for totals)</li> <li>&lt;caption&gt; - a caption or title for the table</li> </ul> <div style="float: right; margin: -10px 0 0 16px;"> <h4>Example Result</h4> <table> <thead> <tr><th>Sample ID</th><th>X</th><th>Y</th></tr> </thead> <tbody> <tr> <td>1</td> <td>5000</td> <td>100</td> </tr> <tr> <td>2</td> <td>6000</td> <td>200</td> </tr> </tbody> <tfoot> <tr> <td>Average</td> <td>5500</td> <td>150</td> </tr> </tfoot> <caption>Example Data Table</caption></table> </div> <h4>Example Code</h4> <pre>&lt;table&gt;<br> &lt;thead&gt;<br> &lt;tr&gt;<br> &lt;th&gt;Sample ID&lt;/th&gt;&lt;th&gt;X&lt;/th&gt;&lt;th&gt;Y&lt;/th&gt;<br> &lt;/tr&gt;<br> &lt;/thead&gt;<br> &lt;tbody&gt;<br> &lt;tr&gt;<br> &lt;td&gt;1&lt;/td&gt;&lt;td&gt;5000&lt;/td&gt;&lt;td&gt;100&lt;/td&gt;<br> &lt;/tr&gt;<br> &lt;tr&gt; &lt;td&gt;2&lt;/td&gt;&lt;td&gt;6000&lt;/td&gt;&lt;td&gt;200&lt;/td&gt; &lt;/tr&gt;<br> &lt;/tbody&gt;<br> &lt;tfoot&gt;<br> &lt;tr&gt;&lt;td&gt;Average&lt;/td&gt;&lt;td&gt;5500&lt;/td&gt;&lt;td&gt;150&lt;/td&gt;&lt;/tr&gt;<br> &lt;/tfoot&gt;<br> &lt;caption&gt;Example Data Table&lt;/caption&gt;<br>&lt;/table&gt;</pre> <h3>Selectors</h3> <p style="font-family: 'Droid Sans', Verdana, Arial, sans-serif; font-size: 13px; font-weight: normal;">Selectors are a way to identify an element in the page. They do nothing in a pure HTML page, but are almost necessary if you want to use CSS or JavaScript along with the page.</p> <h4>Identifier (unique)</h4> <p style="font-family: 'Droid Sans', Verdana, Arial, sans-serif; font-size: 13px; font-weight: normal;">An id attribute must be unique - the only one on the page with that name. They are particularly useful for JavaScript, since the browser provides a way to easily find an element given an ID, but finding a class is slower and harder.</p> <p style="font-family: 'Droid Sans', Verdana, Arial, sans-serif; font-size: 13px; font-weight: normal;">IDs are prefixed by a # (pound) when used in CSS.</p> <p style="font-family: 'Droid Sans', Verdana, Arial, sans-serif; font-size: 13px; font-weight: normal;">The identifier is specified with the id attribute. For example: &lt;img src="/logo.png" id="logo" /&gt; assigns the image the #logo identifier. It should not have spaces or hyphens.</p> <h4>Class (categorical)</h4> <p>A class can be either unique or assigned to multiple elements on the page.</p> <p>classes are prefixed by a . (period) when used in css.&nbsp;</p> <p>The class is specified with the class attribute. Multiple classes can be specified in a single class attribute by using spaces. A class may have a hyphen. For example: &lt;p class="comment new"&gt;Hello&lt;/p&gt; is a paragraph that is both in the .comment class and .new class.</p> <h3 style="color: #333333;">Invisible Tags</h3> <p>It is often extremely useful to organize portions of the page using invisible style-less tags, then define a style specific for the ID or class. In reality, any tag can be made to behave like any other tag by overriding enough styles, but that would be wasteful and difficult to develop.</p> <h4>&lt;div&gt; - Division Block</h4> <p>Div tags are blocks by default. This means that they take up all of the available width and push anything after it to below. They are easier to space between other blocks. Many times these are used to section areas of the page like headings, sidebars, footers, and pages.</p> <h4>&lt;span&gt; - Text</h4> <p>Span tags are inline by default. So, they only take up the space they need and can be used inline with text. For example, &lt;strong&gt;, &lt;em&gt;, &lt;a&gt;, and &lt;img /&gt; are all inline by default. These are mostly useful for highlighting sections of text.</p></div> <section> </section> <div class="field field--name-field-disqus field--type-disqus-comment field--label-above"> <div class="field--label">Disqus</div> <div class="field--item"><drupal-render-placeholder callback="Drupal\disqus\Element\Disqus::displayDisqusComments" arguments="0=HTML%20Introduction&amp;1=http%3A//robotic-controls.com/index.php/learn/programming-concepts/html-introduction&amp;2=node/41" token="mPVAV3B5MVzUaz4j8mGu78deNykT4NXrp-vB9YjVYbg"></drupal-render-placeholder></div> </div> Thu, 28 Feb 2013 16:54:41 +0000 Evan Boldt 41 at http://robotic-controls.com http://robotic-controls.com/index.php/learn/programming-concepts/html-introduction#comments Python Web UI with Tornado http://robotic-controls.com/index.php/learn/python-guis/python-web-ui-tornado <span>Python Web UI with Tornado</span> <div class="field field--name-field-topics field--type-entity-reference field--label-inline"> <div class="field--label">Topics</div> <div class="field--items"> <div class="field--item"><a href="/index.php/topics/python" hreflang="en">Python</a></div> <div class="field--item"><a href="/index.php/topics/web" hreflang="en">Web</a></div> <div class="field--item"><a href="/index.php/topics/serial" hreflang="en">Serial</a></div> <div class="field--item"><a href="/index.php/topics/gui" hreflang="en">GUI</a></div> </div> </div> <span><span lang="" about="/index.php/users/evan-boldt" typeof="schema:Person" property="schema:name" datatype="">Evan Boldt</span></span> <span>Fri, 02/08/2013 - 12:10</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>Introduction</h3> <p>So, you want a GUI for your robot. Sure, you could make a nice GUI in <a href="/learn/basics-gui">Python with Tkinter</a>, but there are some really good reasons to try it as a website instead:</p> <ul> <li>A web GUI can be accessed from almost any location</li> <li>A well-designed web GUI can be used on almost any device like a tablet or a phone</li> <li>HTML, CSS, and Javascript are well documented, powerful, and very flexible</li> <li>HTML can be easily made to look very nice</li> </ul> <p>There are some drawbacks to implementing your GUI as a website though:</p> <ul> <li>It is only able to start communication one-way (browser to server, server responds)</li> <ul> <li>Great for buttons and other input</li> <li>Requres continuous <a href="http://en.wikipedia.org/wiki/Polling_(computer_science)">polling</a> or a <a href="http://en.wikipedia.org/wiki/Comet_(programming)">commet</a> to get data to be pushed to the browser</li> </ul> <li>It adds another "layer" of complexity to your code</li> <ul> <li>Several different languages (C++ on Arduino, Python Server, and HTML+CSS+Javascript in browser)</li> <li>The server has to relay information from the browser to the robot</li> </ul> </ul> <p><!--break--></p> <h3>Installing Python Tornado</h3> <p>I used the <a href="http://www.tornadoweb.org/">Tornado</a> web server for my projects. It is better than just using CGI, since the environment is always loaded while the server is running instead of loading it every time a request is made. CGI would be problematic then, since serial.begin would be run every time a request was made, which simply wouldn't work since the Arduino would also restart all the time.</p> <p>On Ubuntu, the installation is as easy as:</p> <pre>sudo apt-get install python-tornado python-serial</pre> <h3>Using Tornado with the Serial Library</h3> <p>So one of the challenges with this is that reading serial input in python is usually <a href="http://en.wikipedia.org/wiki/Blocking_(computing)">blocking</a>, so the webserver becomes unresponsive to browsers' requests while waiting for serial input.</p> <pre class="code-scroll-tall">#! /usr/bin/python2.7 import os import json import tornado.ioloop import tornado.web from serial import * tornadoPort = 8888 cwd = os.getcwd() # used by static file server # Make a Serial object serialPort = '/dev/ttyACM0' serialBaud = 9600 ser = Serial( serialPort, serialBaud, timeout=0, writeTimeout=0 ) # gets serial input in a non-blocking way serialPending = '' def checkSerial(): try: s = ser.read( ser.inWaiting() ) except: print("Error reading from %s " % serialPort ) return if len(s): serialPending += s paseSerial() #called whenever there is new input to check serialHistory = '' mostRecentLine = '' def parseSerial(): split = serialPending.split("\r\n") if len( split ) &gt; 1: for line in split[0:-1]: print( line ) #do some stuff with the line, if necessary #example: mostRecentLine = line # in this example, status will show the most recent line serialHistory += line pending = split[-1] # send the index file class IndexHandler(tornado.web.RequestHandler): def get(self, url = '/'): self.render('index.html') def post(self, url ='/'): self.render('index.html') # handle commands sent from the web browser class CommandHandler(tornado.web.RequestHandler): #both GET and POST requests have the same responses def get(self, url = '/'): print "get" self.handleRequest() def post(self, url = '/'): print 'post' self.handleRequest() # handle both GET and POST requests with the same function def handleRequest( self ): # is op to decide what kind of command is being sent op = self.get_argument('op',None) #received a "checkup" operation command from the browser: if op == "checkup": #make a dictionary status = {"server": True, "mostRecentSerial": mostRecentLine } #turn it to JSON and send it to the browser self.write( json.dumps(status) ) #operation was not one of the ones that we know how to handle else: print op print self.request raise tornado.web.HTTPError(404, "Missing argument 'op' or not recognized") # adds event handlers for commands and file requests application = tornado.web.Application([ #all commands are sent to http://*:port/com #each command is differentiated by the "op" (operation) JSON parameter (r"/(com.*)", CommandHandler ), (r"/", IndexHandler), (r"/(index\.html)", tornado.web.StaticFileHandler,{"path": cwd}), (r"/(.*\.png)", tornado.web.StaticFileHandler,{"path": cwd }), (r"/(.*\.jpg)", tornado.web.StaticFileHandler,{"path": cwd }), (r"/(.*\.js)", tornado.web.StaticFileHandler,{"path": cwd }), (r"/(.*\.css)", tornado.web.StaticFileHandler,{"path": cwd }), ]) if __name__ == "__main__": #tell tornado to run checkSerial every 10ms serial_loop = tornado.ioloop.PeriodicCallback(checkSerial, 10) serial_loop.start() #start tornado application.listen(tornadoPort) print("Starting server on port number %i..." % tornadoPort ) print("Open at http://127.0.0.1:%i/index.html" % tornadoPort ) tornado.ioloop.IOLoop.instance().start()</pre> <h3>Setting up the Browser</h3> <p>To make it easy to send requests to the server, it's really a good idea to use <a href="http://jquery.com/">jquery</a>, and the easiest way to use jquery is to use the Google API for it. To add jquery to the webpage, just add this script:</p> <pre>&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"&gt;&lt;/script&gt;&nbsp;</pre> <p>So to start, we'll just have a simple webpage that has a div. When the div is clicked, jquery will ask the status of the tornado webserver.</p> <pre class="code-scroll-tall">&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Python Tornado Test Page&lt;/title&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; function serverResponded( data ) { /* log the event data, so you can see what's going on. Shows up in the console on your browser. (Chrome: Tools &gt; Developer Tools &gt; Console) */ console.log( data ); // check the server status, and report it on the screen if ( data.server === true ) { $('#status .value').html("OK"); } else { $('#status .value').html("NOT OK"); } // add the last serial to the div on the screen $('#serial .value').html( data.mostRecentSerial ); } $(document).ready( function() { /* handle the click event on the clickme */ $('#clickme').click( function() { params = { op: "checkup" }; $.getJSON( 'http://localhost:8888/com' , params, serverResponded ); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="clickme" style="cursor: pointer;"&gt;CLICK ME&lt;/div&gt; &lt;div id="status"&gt; Server Status: &lt;span class="value"&gt;?&lt;/span&gt; &lt;/div&gt; &lt;div id="serial"&gt; Last Serial Input: &lt;span class="value"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/body&gt;</pre></div> <section> </section> <div class="field field--name-field-disqus field--type-disqus-comment field--label-above"> <div class="field--label">Disqus</div> <div class="field--item"><drupal-render-placeholder callback="Drupal\disqus\Element\Disqus::displayDisqusComments" arguments="0=Python%20Web%20UI%20with%20Tornado&amp;1=http%3A//robotic-controls.com/index.php/learn/python-guis/python-web-ui-tornado&amp;2=node/30" token="AfviU8SYJhw39dLfL6NBzl_BvF6XAyaKeR5dFV_3dUU"></drupal-render-placeholder></div> </div> Fri, 08 Feb 2013 18:10:44 +0000 Evan Boldt 30 at http://robotic-controls.com http://robotic-controls.com/index.php/learn/python-guis/python-web-ui-tornado#comments