<?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 Devon Fazekas on Medium]]></title>
        <description><![CDATA[Stories by Devon Fazekas on Medium]]></description>
        <link>https://medium.com/@devonfazekas?source=rss-d80dcc5ba400------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rcCNLVGWwJ3L9s7zc9H9rw.jpeg</url>
            <title>Stories by Devon Fazekas on Medium</title>
            <link>https://medium.com/@devonfazekas?source=rss-d80dcc5ba400------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:56:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devonfazekas/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[Building an After-Hours IVR with Twilio]]></title>
            <link>https://medium.com/@devonfazekas/building-an-after-hours-ivr-with-twilio-50a6e55ef274?source=rss-d80dcc5ba400------2</link>
            <guid isPermaLink="false">https://medium.com/p/50a6e55ef274</guid>
            <category><![CDATA[tech-for-business]]></category>
            <category><![CDATA[twilio-automation]]></category>
            <category><![CDATA[work-life-balance]]></category>
            <category><![CDATA[ivr-system]]></category>
            <category><![CDATA[tech-startups]]></category>
            <dc:creator><![CDATA[Devon Fazekas]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 21:36:21 GMT</pubDate>
            <atom:updated>2024-05-24T04:52:42.591Z</atom:updated>
            <content:encoded><![CDATA[<p>Edited May 24, 2024:<br>Resolved the “Cannot read properties of undefined (reading ‘open’)” error.</p><h3>Introduction</h3><p>Running a business is no small feat, especially when customers expect you to be reachable at all hours. While availability is key to great customer service, maintaining a work-life balance is equally important. Here’s where technology comes to the rescue. With Twilio, you can create a simple Interactive Voice Response (IVR) system that directs calls based on your business hours, ensuring that you’re not disturbed during your off-hours.</p><h3>What We’re Building: Any Overview</h3><p>We’ll craft a basic IVR using Twilio that routes incoming calls to your personal phone during business hours, and to a voicemail system after hours. Here’s a simplified outline of our IVR flow:</p><p>1. Caller dials your business number.</p><p>2. IVR checks if it’s within business hours.</p><p>3. If yes, call is forwarded to your personal number.</p><p>4. If no, caller is directed to voicemail.</p><p>Below is a diagram illustrating how the IVR setup connects Twilio Studio, Twilio Functions, and Twilio Assets. This setup manages your call flow, ensuring a seamless operation during business hours while providing a voicemail option after hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLBAAJjb2J0Penj3LoRg3g.png" /><figcaption>Diagram showing the IVR setup: Twilio Studio and Flow for call handling, Twilio Functions for logic processing, and Twilio Assets for storing business hours, ensuring calls reach you only during designated hours.</figcaption></figure><h3>Setting Up Your Twilio Account</h3><p>Ensure you have a business number registered on Twilio. If not, sign up and follow Twilio’s guide to obtain a phone number.</p><h3>Creating a Business Hours Asset</h3><p>We’ll start by creating a file to store, and more importantly, centralize your business’ hours of operation.</p><p>1. Navigate to the Twilio’s <strong>Functions and Assets</strong> &gt; <strong>Services</strong> page.</p><p>2. Create a new <strong>Service</strong> named “<em>IVR</em>”.</p><p>3. Create a new <strong>Asset </strong>file named “<em>HoursOfOperation.json</em>”.</p><p>4. Open the file and paste in the provided template.</p><pre>{<br>  &quot;Monday&quot;: {&quot;open&quot;: 8, &quot;close&quot;: 18},<br>  &quot;Tuesday&quot;: {&quot;open&quot;: 8, &quot;close&quot;: 18},<br>  &quot;Wednesday&quot;: {&quot;open&quot;: 8, &quot;close&quot;: 18},<br>  &quot;Thursday&quot;: {&quot;open&quot;: 8, &quot;close&quot;: 18},<br>  &quot;Friday&quot;: {&quot;open&quot;: null},<br>  &quot;Saturday&quot;: {&quot;open&quot;: 10, &quot;close&quot;: 16},<br>  &quot;Sunday&quot;: {&quot;open&quot;: 8, &quot;close&quot;: 16}<br>}</pre><p>This file contains every day of the week, each with its own open and close hours, in 24-hour format (<em>e.g., 18 represents 6 PM</em>). If your business is closed for an entire day, simply write null as its open, and omit the close.</p><p>5. Save your changes.</p><p>6. Click the <strong>Visibility</strong> button to the right of the asset’s name, then choose “Private”. This step is vital as Twilio’s getAssets()method (used later) only works on private assets.</p><p>7. Deploy your changes.</p><h3>Creating the Time-Check Function</h3><p>Now, we’ll create a function to check the current time against your business hours, and generate a dynamic user-friendly message for the caller in the event that they’ve called after hours.</p><h4>Understanding the Logic</h4><p>Before we dive into the code, the below diagram illustrates a conceptual way to think about the logic flow for the file we’re going to create. In a nutshell, the logic to detect if the business is open is quite simple. The complexity arises in generating a user-friendly message to return to the caller.</p><figure><img alt="Diagram showing steps to determine business availability: reading hours file, comparing current time to business hours, and formatting a user-friendly message." src="https://cdn-images-1.medium.com/max/1024/1*88rkFwgTgt4MowhmWUfr2g.png" /><figcaption>Diagram showing steps to determine business availability: reading hours file, comparing current time to business hours, and formatting a user-friendly message.</figcaption></figure><p>From a caller’s perspective, it is a better experience to be informed not just that the business is closed but when best to call back. This is commonly shown like “<em>Our business hours are: Monday, 9 AM to 5 PM. Tuesday, 9 AM to 5 PM. Wednesday, 9 AM to 5 PM…</em>” and so on. While this is informative, it’ll likely test the caller’s patience.</p><p>We’ll improve this a step further, reducing the message by stating date ranges that share the same hours, resulting in something like “<em>Our business hours are Monday through Friday, 9 AM to 5 PM</em>”.</p><h4>Create the Function</h4><p>1. In Twilio’s <strong>Functions and Assets</strong>, create a new <strong>Function </strong>named “<em>BusinessHoursHandler</em>”.</p><p>2. Paste in the following code. You don’t need to modify anything.</p><pre>const days = new Map([<br>  [0, &#39;Monday&#39;],<br>  [1, &#39;Tuesday&#39;],<br>  [2, &#39;Wednesday&#39;],<br>  [3, &#39;Thursday&#39;],<br>  [4, &#39;Friday&#39;],<br>  [5, &#39;Saturday&#39;],<br>  [6, &#39;Sunday&#39;]<br>])<br><br>function aggregateBusinessHours(hoursOfOperation) {<br>  let previousHours = null<br>  let currentGroup = []<br>  const groupedHours = []<br><br>  for (let i = 0; i &lt; 7; i++) {<br>    const day = days.get(i)<br>    const hours = hoursOfOperation[day]<br>    const hoursString =<br>      hours &amp;&amp; hours.open &amp;&amp; hours.close<br>        ? `${convertTo12Hour(hours.open)} AM to ${convertTo12Hour(<br>            hours.close<br>          )} PM`<br>        : &#39;Closed&#39;<br><br>    if (hoursString !== previousHours) {<br>      if (currentGroup.length &gt; 0) {<br>        groupedHours.push({ days: currentGroup, hours: previousHours })<br>        currentGroup = []<br>      }<br>      previousHours = hoursString<br>    }<br><br>    currentGroup.push(day)<br>  }<br><br>  if (currentGroup.length &gt; 0) {<br>    groupedHours.push({ days: currentGroup, hours: previousHours })<br>  }<br><br>  return groupedHours<br>}<br><br>function formatBusinessHours(groupedHours) {<br>  const openGroups = []<br>  const closedGroups = []<br><br>  const formatGroup = (group) =&gt; {<br>    const days = group.days<br>    const formattedDays =<br>      days.length &gt; 1 ? `${days[0]} through ${days[days.length - 1]}` : days[0]<br>    return group.hours === &#39;Closed&#39;<br>      ? formattedDays<br>      : `${formattedDays}, ${group.hours}`<br>  }<br><br>  for (const group of groupedHours) {<br>    const formattedGroup = formatGroup(group)<br>    if (group.hours === &#39;Closed&#39;) {<br>      closedGroups.push(formattedGroup)<br>    } else {<br>      openGroups.push(formattedGroup)<br>    }<br>  }<br><br>  let hoursString = openGroups.join(&#39;, &#39;)<br><br>  if (closedGroups.length &gt; 0) {<br>    hoursString += &#39;, and closed &#39; + closedGroups.join(&#39;, &#39;)<br>  }<br><br>  return hoursString<br>}<br><br>function convertTo12Hour(time) {<br>  return time % 12 || 12<br>}<br><br>exports.handler = function (context, event, callback) {<br>  // Grab the current date and time. Note that this is the local time where the<br>  // Function is being executed, not necessarily the time zone of your business!<br>  const now = new Date()<br><br>  // Configure Intl.DateTimeFormat to return a date in the specified<br>  // time zone and in this format for parsing, for example: &#39;Monday, 18&#39;<br>  const formatOptions = {<br>    hour: &#39;numeric&#39;,<br>    hour12: false,<br>    weekday: &#39;long&#39;,<br>    timeZone: &#39;America/Toronto&#39;<br>  }<br>  const formatter = new Intl.DateTimeFormat(&#39;en-US&#39;, formatOptions)<br><br>  // Get the current time and currentDay of the week for your specific time zone<br>  const formattedDate = formatter.format(now).split(&#39;, &#39;)<br>  const currentDay = formattedDate[0] // ex. &#39;Monday&#39;<br>  const currentHour = Number(formattedDate[1]) // ex. 18<br><br>  // Read the hours-of-operation from the asset file.<br>  const openFile = Runtime.getAssets()[&#39;/HoursOfOperation.json&#39;].open<br>  const hoursOfOperation = JSON.parse(openFile())<br>  const todayHours = hoursOfOperation[currentDay]<br>  let hoursString = &#39;&#39;<br><br>  // Determine if the business is open based on today&#39;s hours.<br>  const isOpen =<br>    todayHours &amp;&amp;<br>    currentHour &gt;= todayHours.open &amp;&amp;<br>    currentHour &lt; todayHours.close<br>  // If closed, build a user-friendly response.<br>  if (!isOpen) {<br>    const groupedHours = aggregateBusinessHours(hoursOfOperation)<br>    hoursString = `Our business hours are ${formatBusinessHours(groupedHours)}.`<br>  }<br><br>  console.log(&#39;isOpen:&#39;, isOpen, &#39;hoursString:&#39;, hoursString)<br>  return callback(null, { isOpen, hoursString })<br>}</pre><p>3. Save and deploy again.</p><h3>Building the IVR System</h3><p>1. Navigate to Twilio’s <strong>Studio</strong> &gt; <strong>Flows</strong> page.</p><p>2. Create a new <strong>Flow</strong> named “<em>IVR</em>”.</p><p>3. Select the <strong>Start From Scratch</strong> option.</p><h4>Integrating the Function</h4><p>We’re ready to use our function for handling incoming calls.</p><figure><img alt="Screenshot of configuring the get_business_hours (Run Function) widget inside Twilio Studio." src="https://cdn-images-1.medium.com/max/577/1*Zpxfe5m2a6gcsM9mr58oeg.png" /><figcaption>Screenshot of configuring the <strong><em>get_business_hours</em></strong> (Run Function) widget inside Twilio Studio.</figcaption></figure><p>1. Start by scrolling through the Widget Library panel, and dragging a <strong>Run Function</strong> widget onto the canvas.</p><p>2. Click on the <strong>Run Function</strong> <strong>widget </strong>you just placed, opening its Config panel. Rename this widget as “<em>get_business_hours</em>”.</p><p>3. Set its Service field to your “<em>IVR”</em> Service, its Environment field to “<em>ui</em>”, and its Function field to your “<em>BusinessHoursHandler</em>” function.</p><p>4. Save the widget’s changes.</p><p>5. Now click on the <strong>Trigger</strong> widget and navigate to its Transitions panel.</p><p>6. Set its IF INCOMING CALL field to your <strong><em>get_business_hours</em> </strong>widget. Then save the changes.<br>This essentially triggers our function immediately after receiving a call.</p><h4>Directing the Call</h4><p>Now we’ll check the result of our function and decide how to handle the incoming call.</p><figure><img alt="Screenshot of configuring the “check_business_hours” (Split Based On) widget." src="https://cdn-images-1.medium.com/max/350/1*Z_xuFRXFY-QQcVogo-p9RA.png" /><figcaption>Screenshot of configuring the <strong>check_business_hours</strong> (Split Based On) widget.</figcaption></figure><p>1. From the Widget Library, drag a <strong>Split Based On</strong> widget onto the canvas, naming it “<em>check_business_hours</em>”.</p><p>2. In its Config panel, set its VARIABLE TO TEST field to widgets.get_business_hours.parsed.isOpen and save.<br>This essentially reads the isOpen result from our function, which holds either the value True or False (<em>case sensitive</em>).</p><p>3. In its Transitions panel, create new <strong>Condition</strong>. Configure as follows: Condition as “Equal To”, Value as “True” (<em>omit quotation marks</em>), and its Transition field we’ll set later. Click <strong>Set Condition</strong> to save your changes. Then click Rename to rename this Condition to “<em>IF OPEN</em>”, then click <strong>Set Condition</strong> once more to resave.</p><p>4. Create another <strong>Condition </strong>named “<em>IF CLOSED</em>” with the following configuration: Condition as “Equal To”, Value as “False” (<em>omit quotation marks</em>), and its Transition field left empty (again, we’ll set later). Click <strong>Set Condition</strong> to save.</p><p>5. Set the IF SUCCESS transition on the <strong><em>get_business_hours</em></strong> widget to this widget.</p><h4>Redirecting to Voicemail</h4><p>The caller will only reach this branch if they’ve called after hours. In this event, we’ll have the caller leave a voicemail.</p><figure><img alt="Screenshot of configuring the IF-CLOSED branch." src="https://cdn-images-1.medium.com/max/521/1*gKqsP-KSAim66yQZXX1uZg.png" /><figcaption>Screenshot of configuring the IF-CLOSED branch.</figcaption></figure><p>1. From the Widget Library, drag a <strong>Say/Play</strong> widget onto the canvas, and name it “<em>say_closed</em>”.</p><p>2. In its Config panel, set its TEXT TO SAY value to the following script, then save.<br>The first component of this script reads the hoursString result from our earlier function which contains the user-friendly message.</p><pre>{{widgets.get_business_hours.parsed.hoursString}}. Stay on the line to leave a message or call back later.</pre><p>3. You can now connect the IF CLOSED transition from the <strong><em>check_business_hours</em></strong> widget to this widget.</p><p>4. Then drag a <strong>Record Voicemail</strong> widget onto the canvas, naming it “<em>record_voicemail</em>”.</p><p>5. Connect the IF AUDIO COMPLETE transition from the <strong><em>say_closed</em></strong> widget to this widget.</p><p>6. Your setup should now look like the screenshot at the top of this section.</p><h4>Redirecting to the Business Owner</h4><p>Like the previous branch, callers will only reach here in the event they call during business hours.</p><figure><img alt="Screenshot of configuring the IF-OPEN branch." src="https://cdn-images-1.medium.com/max/491/1*9PjyPn3lOjGnxm35IWnlTw.png" /><figcaption>Screenshot of configuring the IF-OPEN branch.</figcaption></figure><p>1. Drag a <strong>Connect Call To widget</strong> onto the canvas, naming it “<em>connect_call_to_owner</em>”.</p><p>2. Set its CONNECT CALL TO field to any phone number you want.</p><p>3. You can now connect the IF OPEN transition from the <strong><em>check_business_hours </em></strong>widget to this widget.</p><p>4. Your setup should look like the above screenshot.</p><h3>Integrating the Business Phone</h3><p>You’re almost done. By this point, you’ll have a complete (albeit simple) IVR system that conditionally directs callers based on the time of day and your business hours. Lastly, you need to attach your Twilio business phone number to this Flow.</p><p>1. Navigate to Twilio’s <strong>Phone Numbers</strong> &gt; <strong>Manage </strong>&gt; <strong>Active numbers</strong> page.</p><p>2. Click on your active phone number to configure it.</p><p>3. Within its <strong>Voice Configuration</strong> section, configure it as follows: CONFIGURE WITH value as “Webhook, TwiML Bin, Function, Studio Flow, Proxy Service”, its A CALL COMES IN as “Studio Flow”, FLOW as “IVR”, and leave the rest of fields as default.</p><p>4. Scroll to the bottom and save your configuration.</p><h3>Conclusion</h3><p>In conclusion, deploying an IVR system with Twilio not only enhances your business’s professionalism but also ensures a balanced lifestyle amidst your entrepreneurial journey. This setup acts as a courteous, informative assistant to your callers, whether you’re available or not. Now, every call to your business number is smartly handled, allowing you to focus on other vital aspects of your business while keeping your customers informed.</p><p>As a business owner, leveraging the power of technology is pivotal in staying ahead of the curve. Our journey doesn’t end here. Explore more articles on this blog to uncover a plethora of innovative solutions tailored to propel your business into a future of endless possibilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50a6e55ef274" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Tutorial — Learn how to create a Notion Wiki for Guild Wars 2 (part 3)]]></title>
            <link>https://medium.com/@devonfazekas/api-tutorial-learn-how-to-create-a-notion-wiki-for-guild-wars-2-part-3-42999cf36c2b?source=rss-d80dcc5ba400------2</link>
            <guid isPermaLink="false">https://medium.com/p/42999cf36c2b</guid>
            <category><![CDATA[notion-api]]></category>
            <category><![CDATA[notion]]></category>
            <category><![CDATA[guild-wars-2]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Devon Fazekas]]></dc:creator>
            <pubDate>Fri, 23 Dec 2022 01:51:09 GMT</pubDate>
            <atom:updated>2022-12-23T01:56:05.134Z</atom:updated>
            <content:encoded><![CDATA[<h3>API Tutorial — Learn how to create a Notion Wiki for Guild Wars 2 (part 3)</h3><p>Getting Started with the Notion API.</p><figure><img alt="Banner." src="https://cdn-images-1.medium.com/max/1024/1*C_akWfEVDl_U5FugiukbjQ.png" /></figure><h3>Introduction</h3><p>Welcome to <strong>Part 3</strong> of this blog series! In this part, we’ll explore how to set up the Notion API.</p><p>In <a href="https://medium.com/@devonfazekas/api-tutorial-learn-how-to-create-a-notion-wiki-for-guild-wars-2-part-2-3bdbf22b9b51"><strong>Part 2</strong></a>, we interacted with the public API endpoints offered by Guild Wars 2, so there was no need for security clearances. In this part, however, we’ll be modifying our personal Notion pages, so security is a must. We don’t want strangers to be able to view and modify our databases. This step-by-step tutorial will help you get the Notion API set up quickly.</p><p>If you have not read part 2 of our series, check it out here:<br><a href="https://medium.com/@devonfazekas/api-tutorial-learn-how-to-create-a-notion-wiki-for-guild-wars-2-part-2-3bdbf22b9b51"><strong>Part 2 — Getting Started with the Guild Wars 2 API</strong></a>.</p><h3>Creating a Notion Integration</h3><p>Notion provides an API that can be used to interact with Notion pages and databases. To leverage their API, Notion also introduced Integrations to help control which pages can be accessed through the API.</p><p>Many other companies like Dropbox and Make have already created their own integrations, allowing for synchronization and automations between their services and Notion. You can find the full listing of available integrations here: <a href="https://www.notion.so/integrations/all">https://www.notion.so/integrations/all</a>.</p><p>To get started with the Notion API, you need to create your own Notion integration and give it access to your Notion workspace. This can be accomplished by following their documentation (<a href="https://www.notion.so/my-integrations">https://www.notion.so/my-integrations</a>).</p><p>An integration requires a name, an associated workspace, and a list of capabilities. The following screenshot shows the setup needed for our purposes. For the name, I’ve chosen “GW2 Wiki Builder”, the associated workspace is simply the parent workspace of your Guild Wars 2 page, and for capabilities, we only need to insert content, but it’s nice to have the option for updating and reading content later.</p><figure><img alt="Screenshot of creating Notion integrations." src="https://cdn-images-1.medium.com/max/394/1*LJ0Zl05WgRMlJnDCqumobg.png" /><figcaption>Screenshot of creating Notion integrations.</figcaption></figure><p>After submitting your configurations, you’ll be provided with a secret integration token that looks like this: secret_NUJXQCTlgUi.V2F5reGnxUB7FYSqaek2aT. <br>Copy and paste it somewhere safe for later use.</p><h3>Set up a Notion Wiki</h3><p>In this series, we only explore the Guild Wars 2 /items endpoint. However, there are many more endpoints offered by their API. By the end of this series, you will have the skills and knowledge to work with those other endpoints. To accommodate this, we&#39;ll design our Notion wiki to be expandable.</p><p>To start, create a page in Notion titled “Guild Wars 2”. This will serve as the Wiki’s home page.</p><figure><img alt="Screenshot of the Notion page for Guild Wars 2." src="https://cdn-images-1.medium.com/max/546/1*TkLnQO5dUYcDquw-3Y2hBQ.png" /><figcaption>Screenshot of the Notion page for Guild Wars 2.</figcaption></figure><p>Then, inside the “Guild Wars 2” page, create another page titled “Items” to serve as a database for GW2 items. In this page, be sure to select “Table” to convert the plain page into a database.</p><figure><img alt="Screenshot of creating a table database in Notion." src="https://cdn-images-1.medium.com/max/1024/1*pTbDTopWsU5R7hqyyclf-A.png" /><figcaption>Screenshot of creating a table database in Notion.</figcaption></figure><h3>Connect your Integration to the Wiki</h3><p>Once you have created your integration, you need to grant it explicit access to the pages you want it to be able to modify. Because we’ll want it to modify our Items database and also possibly other databases in the future, we’ll connect the integration to the entire Wiki page, so it’ll have access to all subpages in the future.</p><p>Return to the Guild Wars 2 Notion page (refresh if needed). To connect the integration, open the options menu in the top-right corner, then select the “Add connections” option and choose the “GW2 Wiki Builder” integration.</p><figure><img alt="Screenshot of adding integrations into Notion." src="https://cdn-images-1.medium.com/max/1024/1*BoGyj_vCoGe1FArLFNf6eg.png" /><figcaption>Screenshot of adding integrations into Notion.</figcaption></figure><p>At this point, we can make API requests to Notion, similar to how we did with Guild Wars 2. However, we need to provide Postman with authentication parameters to prevent Notion from blocking the requests. We’ll handle this shortly.</p><h3>Getting the Database ID</h3><p>When dealing with databases through the API, Notion requires specifying the ID of the database. The question then is: where do we find this ID? Unfortunately, the answer is not straightforward. However, this article <a href="https://neverproductive.com/database-id-notion/">https://neverproductive.com/database-id-notion/</a> provides a clear explanation of where to find the ID and how to extract it.</p><p>In a nutshell, Notion embeds the database ID within the URL. So first, navigate to the Items database in Notion (if you haven’t already, turn this page into a table database).</p><p>Depending on your Notion settings, the URL of this page may look differently but the steps to extract database ID remain the same. The steps include:</p><ol><li>Find the last forward slash (/). Delete it along with everything before it.</li><li>Find the question mark (?). Delete it and everything after.</li></ol><h4>Example</h4><p>If your database page URL looks like the text below, then the database ID is the red section. Copy this ID and store it securely for future use.</p><p><a href="https://www.notion.so/devonfazekas/3d63f7b561d24f3eb39072986f088a4b?v=65769c7858da4162a59977ad9f45c1ea">https://www.notion.so/devonfazekas/3d63f7b561d24f3eb39072986f088a4b?v=65769c7858da4162a59977ad9f45c1ea</a></p><h3>Setting up Postman for Notion</h3><p>In this section, we’ll go through the steps to authorize Postman to use Notion’s APIs. We’ll need to provide Postman with authentication parameters to prevent Notion from blocking the requests. To do this, we’ll create a new Collection in Postman and add the integration token we created earlier.</p><h4>Authorize Postman</h4><p>As previously mentioned, Notion will block all unknown senders of API requests to protect your personal data. To authorize Postman, click on your Notion Collection. Under the <strong>Authorization </strong>tab, change the type to Bearer Token and paste your secret key into the <strong>Token </strong>field. Save your changes.</p><figure><img alt="Screenshot of adding Notion authorization tokens in Postman." src="https://cdn-images-1.medium.com/max/1024/1*m5YLnLK1xQKfnA4rJn272g.png" /><figcaption>Screenshot of adding Notion authorization tokens in Postman.</figcaption></figure><h4>Test the Notion API</h4><p>The Notion API offers many endpoints to play with. Check out their documentation for the full list: <a href="https://developers.notion.com/reference/intro">https://developers.notion.com/reference/intro</a>.</p><p>Let’s try a test request to ensure success in our setup. In Postman, create a new request titled “Query Database” within your Notion collection. <em>Note: If you create a request outside the collection, it won’t inherit the authorization token and will be blocked.</em></p><p>The URL for the endpoint is https://api.notion.com/v1/databases/:id/query, which should return information about our database. According to the documentation, this is a <strong>POST</strong> type, not a <strong>GET</strong> type like before, so be sure to choose that option next to the endpoint’s URL section.</p><p>This URL has a path variable, denoted by a colon and the variable name (e.g. :id). You can see it identified in the <strong>Params </strong>tab in Postman. Referring back to the documentation, this path variable expects the ID of a database. Paste the database ID into its value.</p><figure><img alt="Screenshot of adding path parameters in Postman." src="https://cdn-images-1.medium.com/max/1024/1*G32Or7AUB5F8gvVDjWpP6A.png" /><figcaption>Screenshot of adding path parameters in Postman.</figcaption></figure><p>If you tried to send this request now (go ahead and try), Notion would return an error, stating that the request is missing the version number. The documentation elaborates on why a version number is necessary, and what value it expects. Simply add Notion-Version as the key under the <strong>Headers </strong>tab, with a value of 2022-02-22. Your setup should match the image below.</p><figure><img alt="Screenshot of successful API request test for Notion in Postman." src="https://cdn-images-1.medium.com/max/1024/1*bKgD2bHCAHG1xHTv_fl-yA.png" /><figcaption>Screenshot of successful API request test for Notion in Postman.</figcaption></figure><p>Press [Send] to send the request. If all is correct, you’ll see 200 OK in the status, and the JSON response object below it.</p><h3>Conclusion</h3><p><strong>Congratulations!</strong> 🎉 You now have the Notion API set up and ready to go. In the next part of this series, we’ll start designing our Notion database to store the data we get from the Guild Wars 2 API. See you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42999cf36c2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Tutorial — Learn how to create a Notion Wiki for Guild Wars 2 (part 2)]]></title>
            <link>https://medium.com/@devonfazekas/api-tutorial-learn-how-to-create-a-notion-wiki-for-guild-wars-2-part-2-3bdbf22b9b51?source=rss-d80dcc5ba400------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bdbf22b9b51</guid>
            <category><![CDATA[guild-wars-2]]></category>
            <category><![CDATA[notion]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Devon Fazekas]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 02:44:53 GMT</pubDate>
            <atom:updated>2022-12-23T01:53:49.004Z</atom:updated>
            <content:encoded><![CDATA[<h3>API Tutorial — Learn how to create a Notion Wiki for Guild Wars 2 (part 2)</h3><h4>Getting Started with the Guild Wars 2 API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZO7tA__TPT7bV8upUq8Fkw.png" /></figure><h3>Introduction</h3><p>In this part 2 of our series, we will provide an introduction to the Guild Wars 2 (GW2) API, and explain how to get started with it. Whether you are a fan of the game or a developer interested in creating applications to use with the API, this blog post will provide the necessary background and steps to get started.</p><p>If you have not seen part 1 of our series, check it out here:<br><a href="https://medium.com/@devonfazekas/api-tutorial-learn-how-to-create-a-notion-wiki-for-guild-wars-2-part-1-d07ef5eb048d">Part 1 — Understanding APIs, Postman, and Notion for Guild Wars 2 Wiki</a>.</p><h3>Getting Started with GW2 API</h3><p>The first step is to find an API that supports Guild Wars 2. A good way to do this is to search for “Guild Wars 2 APIs” on a search engine. The following link is one such API for Guild Wars 2: <a href="https://wiki.guildwars2.com/wiki/API:Main">https://wiki.guildwars2.com/wiki/API:Main</a>. Within this page includes a wealth of documentation on what services their API offers, including instructions on their usage, expected responses, and any limitations. This API specifically offers both general usage and user-based usage which requires authentication. Since we’re creating a general wiki for items and locations within the game (not related to any particular player), we’ll only utilize the general services, hence we won’t require an API key.</p><h3>Calling the API</h3><p>The main page of the Guild Wars API documentation lists the available versions of the API. Currently, version-2 is the latest. Viewing its page (<a href="https://wiki.guildwars2.com/wiki/API:2">https://wiki.guildwars2.com/wiki/API:2</a>), we see that the base URL for all its endpoints starts with https://api.guildwars2.com/v2.</p><p>The first API request we’ll try is to retrieve all the items in Guild Wars 2. Navigating through the version-2 of the documentation, you should find a page dedicated to items (<a href="https://wiki.guildwars2.com/wiki/API:2/items">https://wiki.guildwars2.com/wiki/API:2/items</a>). Here, we see that the endpoint to request all items is /items. Appending this onto the base URL above, the complete API request looks like this: https://api.guildwars2.com/v2/items.</p><p>Paste this API request into the search bar of your browser. As shown below, you’ll receive a JSON data containing a list of numbers which represents the IDs of each item in Guild Wars 2.</p><figure><img alt="Screenshot of item IDs from GW2." src="https://cdn-images-1.medium.com/max/430/1*4j804YfrDcRc-rRFBWqSow.png" /><figcaption>Screenshot of item IDs from GW2.</figcaption></figure><p>Voila! You’ve successfully sent your first API request. But you may be correctly wondering how these IDs can help us achieve our original goal of getting information about items.</p><p>Thankfully, this API enables us to query for specific items using their IDs. We need to provide additional information via parameters. The documentation states that this endpoint supports a ids query parameter, which takes a comma-separated list of item IDs.</p><p>Query parameters are denoted by a question mark (?) followed by the query name, then an equal sign (=). For example, to query for the item represented by ID 4, the URL would be https://api.guildwars2.com/v2/items?ids=4.</p><p>The following screenshot shows the JSON response of this request, which includes values such as the item’s name, type, rarity, and so on.</p><figure><img alt="Screenshot of item data from GW2 API." src="https://cdn-images-1.medium.com/max/764/1*VDOql4SKRnDW18AxPc72cg.png" /><figcaption>Screenshot of item data from GW2 API.</figcaption></figure><p>Moving forward, we’ll continue to use many APIs between Guild Wars 2 and Notion. To simplify tracking requests and providing necessary parameters, we’ll set up Postman. This will help us categorize and streamline our API requests.</p><h3>Getting Started with Postman</h3><p>Once you install Postman, you should see a screen similar to the screenshot below.</p><p>We’ll start by creating a new Collection. Collections in Postman are a way to organize and manage your API requests. They’re useful for grouping related requests in one place and for quickly finding and accessing them.</p><p>For example, you could create a “Guild Wars 2” Collection to store all the API requests related to the game, and another called “Notion” for storing all APIs requests related to that tool.</p><figure><img alt="Screenshot of Postman." src="https://cdn-images-1.medium.com/max/1024/1*aiDGO4y9RKnqh84wwvKZXA.png" /><figcaption>Screenshot of Postman.</figcaption></figure><p>In the “Guild Wars 2” Collection, create two Requests for the two APIs used previously. Name them something intuitive, such as “Get All Item IDs” and “Get Items by IDs”.</p><h4>Get All Item IDs</h4><p>For the first request (“Get all item IDs”), paste the URL into the page. Set the request type to “GET” and press [Send]. You should see the same JSON list of numbers as before.</p><figure><img alt="Screenshot of requesting item IDs from Guild Wars 2 in Postman." src="https://cdn-images-1.medium.com/max/703/1*RsS1JEsgQZJi74GxNrzgxw.png" /><figcaption>Screenshot of requesting item IDs from Guild Wars 2 in Postman.</figcaption></figure><h4>Get Items by IDs</h4><p>For the second request (“Get items by ID”), paste the URL like before. This time, you’ll notice in the <strong>Query Params</strong> section, our query parameter ids and its value 4 are extracted into a row. Press [Send] to return the JSON item info, just like before.</p><figure><img alt="Screenshot of requesting item info from Guild Wars 2 in Postman." src="https://cdn-images-1.medium.com/max/704/1*16MuayBh38VUX_M_OhxGmQ.png" /><figcaption>Screenshot of requesting item info from Guild Wars 2 in Postman.</figcaption></figure><p>Now that we have successfully communicated with the Guild Wars 2 API server, we can use Notion to create pages based on this data.</p><h3>Conclusion</h3><p>Congratulations! 🎉🎊 We have successfully communicated with the Guild Wars 2 API server, allowing us to extract the data we need for our wiki. In the next part of this series we’ll explore how to set up the Notion API. Head over to <a href="https://medium.com/@devonfazekas/api-tutorial-learn-how-to-create-a-notion-wiki-for-guild-wars-2-part-3-42999cf36c2b"><strong>Part 3 — Getting Started with the Notion API</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bdbf22b9b51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Tutorial — Learn how to create a Notion Wiki for Guild Wars 2 (part 1)]]></title>
            <link>https://medium.com/@devonfazekas/api-tutorial-learn-how-to-create-a-notion-wiki-for-guild-wars-2-part-1-d07ef5eb048d?source=rss-d80dcc5ba400------2</link>
            <guid isPermaLink="false">https://medium.com/p/d07ef5eb048d</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[guild-wars-2]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[notion]]></category>
            <category><![CDATA[postman]]></category>
            <dc:creator><![CDATA[Devon Fazekas]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 08:13:29 GMT</pubDate>
            <atom:updated>2022-12-22T02:46:01.125Z</atom:updated>
            <content:encoded><![CDATA[<h3>API Tutorial — Learn how to create a Notion Wiki for Guild Wars 2 (part 1)</h3><h4>Understanding APIs, Postman, and Notion for Guild Wars 2 Wiki</h4><figure><img alt="Volume 1 logo of this series." src="https://cdn-images-1.medium.com/max/1024/1*y7BjGBxd2njIGVYw0-BxKQ.png" /></figure><h3>Introduction</h3><p>Guild Wars 2 is an incredibly popular massively multiplayer online role-playing game (MMORPG) with millions of players around the world. With the help of APIs, it is possible to create a Notion wiki that contains all the necessary information players need to know in order to make the most of the game. In this blog series, we will look at how to create a Notion wiki for Guild Wars 2 using APIs.</p><figure><img alt="Data flow from Guild Wars 2 to Notion." src="https://cdn-images-1.medium.com/max/1024/1*bD2V2I9lTBabVSln_fbNxQ.png" /></figure><p>This blog series is written in such a way that you don’t need to be a programmer to follow along. We will provide step-by-step instructions with screenshots, making it easy for anyone to create their own Notion wiki for Guild Wars 2.</p><p>This blog post provides background knowledge on APIs, Postman, Notion, and Guild Wars 2. In the second post, we will look at how to set up the Guild Wars 2 API. The third post will provide a tutorial for getting started with Notion’s API. And the last post will show how to bring all of this information together into a complete Notion Wiki system.</p><h3>What is Guild Wars 2? 🐉</h3><p>Guild Wars 2 is an MMORPG developed by ArenaNet. It is set in the fantasy world of Tyria, where players create characters to explore the world, complete quests, and battle monsters and other players. The game features an open world with a rich narrative, dynamic events, competitive player-versus-player combat, and cooperative group gameplay. Players can customize their characters with a variety of weapons, armor, and skills, and can join Guilds to cooperate and compete with other players. Guild Wars 2 also features an in-game economy, allowing players to purchase and trade virtual goods.</p><p><strong>Play for free:</strong> <a href="https://www.guildwars2.com/">https://www.guildwars2.com</a></p><h3>What is an API?</h3><p>An API, or application programming interface, is a set of protocols and tools used to build software applications. APIs allow developers to access and manipulate data from other programs, websites, and databases. APIs can be used to create a Notion wiki for Guild Wars 2, as they provide an efficient way to access information from the game’s servers and create pages in Notion.</p><p>There are various types of APIs that can be used to create a Notion wiki for Guild Wars 2. Some APIs are available to the general public and can be used without authentication or payment. Other APIs require authentication, such as an API key, in order to access the data. Finally, some APIs are paid services and require a fee for use. Be sure to read the terms of use for any API before using it.</p><figure><img alt="People sharing data." src="https://cdn-images-1.medium.com/max/292/1*gRUwOCM7RNyFkGTC9Gm75A.png" /></figure><p>Finding an API for a specific topic is relatively easy. A good place to start is to search for “[topic name] APIs” on a search engine. This should bring up a list of available APIs. Additionally, there are several websites that specialize in listing APIs, such as <a href="https://www.programmableweb.com/category/all/apis">ProgrammableWeb</a> and <a href="https://rapidapi.com/">RapidAPI</a>. These websites can provide a comprehensive list of available APIs.</p><p>When making requests to an API, the response from the server is usually in the form of JSON data, so it’s important to understand how to read and write in this format when using APIs.</p><p>With some practice and a bit of creativity, you can create amazing things with APIs.</p><h3>Understanding JSON Data</h3><p>JSON stands for <strong>JavaScript Object Notation</strong>. It is a way for servers and apps to send data to each other.</p><p>While APIs provide the means to communicate between different systems, JSON is the language that is used to format the messages being exchanged. JSON lets developers create or read data that computers can understand. It is lightweight and becoming more popular because it is easy to read and write. The structure of JSON is based on two data structures: the <strong>object </strong>and the <strong>array</strong>; it is also a language-independent format, which means it works with any programming language.</p><p>JSON data is composed of key-value pairs (KEY : VALUE) separated by commas, and organized into a tree-like structure. The keys are strings (<em>i.e., wrapped with quotation marks</em>) that represent the data, while the values are the actual data stored. This data can be of any type, such as numbers, strings, objects, arrays, and even other JSON files, making JSON a very powerful and versatile tool for storing data.</p><h4>Example</h4><p>John Doe is a fictitious character designed to help you better understand JSON data. He is a 30-year-old father whose favorite colors are blue, green, and red. His address is 123 Main St, New York, NY. His only child’s name is Sarah. The JSON data below captures all of this information in an intuitive structure.</p><pre>{<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;age&quot;: 30,<br>    &quot;favourite colours&quot;: [ &quot;blue&quot;, &quot;green&quot;, &quot;red&quot; ],<br>    &quot;address&quot;: {<br>        &quot;street number&quot;: 123,<br>        &quot;street name&quot;: &quot;Main St&quot;,<br>        &quot;city&quot;: &quot;New York&quot;,<br>        &quot;state&quot;: &quot;NY&quot;<br>    },<br>    &quot;children&quot;: [<br>        {<br>            &quot;name&quot;: &quot;Sarah Doe&quot;,<br>            &quot;age&quot;: 12<br>        }<br>    ]<br>}</pre><p>In JSON, values can be represented in various data types, including strings, numbers, arrays, and objects.</p><ul><li>A <strong>string</strong> is a sequence of characters enclosed in quotation marks. In JSON, all keys must be strings. In our example, most of the pairs contain strings, such as name: &quot;John Doe&quot; and address.city: &quot;New York&quot;.</li><li>A <strong>number</strong> is a numerical value that can be a whole number or a decimal. In our example, we use numbers for age and address.number.</li><li>An <strong>array</strong> is a list of values enclosed in square brackets. In this example, we use arrays for both favourite colors and children. The values of an array are indexed, starting at zero. To retrieve the first colour, we say address[0] and address[2] for the third colour.</li><li>Nested <strong>objects </strong>can be retrieved by using the dot notation. This involves naming the parent object and then a period (.) followed by the name of the property you wish to retrieve. In our example, this means that you can access the name of the first child in the array by saying children[0].name.</li></ul><p>Once the data is read, it can be manipulated and used in various ways. With practice and a bit of creativity, you can create amazing things with JSON data.</p><h3>What is Postman?</h3><p>Postman is a powerful API development and testing tool that helps users make API calls, build and test API requests, and validate API responses. It simplifies the process of working with APIs and allows developers to quickly create, debug, and test API requests. Postman offers an intuitive user interface, allowing users to easily write and send API requests, view responses, and store and share API requests. It also has comprehensive documentation and tutorials to help users get started. Postman is a great tool for developers working with APIs, and is essential for creating a Notion wiki for Guild Wars 2.</p><p><strong>Download for free</strong>: <a href="https://www.postman.com/downloads">https://www.postman.com/downloads</a></p><h3>What is Notion?</h3><p>Notion is a powerful cloud-based tool for creating and managing content in a wiki-style format. It allows users to easily organize and connect content, create and manage databases, and collaborate with others. Notion is highly customizable and user-friendly, making it an ideal platform for creating a wiki for games like Guild Wars 2. It provides an intuitive way to structure and design content, which makes it easy to keep track of information and access it quickly.</p><p><strong>Sign up for free:</strong> <a href="https://www.notion.so/signup">https://www.notion.so/signup</a></p><h3>Conclusion 💯</h3><p>Now that you have a better understanding of APIs, Postman, and Notion, you are ready to start creating your own Notion wiki for Guild Wars 2. In the next post, we will look at how to set up the Guild Wars 2 API and then move on to a tutorial for getting started with Notion’s API. Finally, we will bring everything together into a complete Notion Wiki system. Head over to <a href="https://medium.com/@devonfazekas/api-tutorial-learn-how-to-create-a-notion-wiki-for-guild-wars-2-part-2-3bdbf22b9b51">Part 2 — Getting Started with the Guild Wars 2 API</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d07ef5eb048d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulating dynamic vehicular detours based on edge travel time in SUMO]]></title>
            <link>https://medium.com/@devonfazekas/simulating-dynamic-vehicular-detours-based-on-edge-travel-time-in-sumo-e57a50457dba?source=rss-d80dcc5ba400------2</link>
            <guid isPermaLink="false">https://medium.com/p/e57a50457dba</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[network-traffic]]></category>
            <category><![CDATA[traffic-simulation]]></category>
            <category><![CDATA[netedit]]></category>
            <category><![CDATA[sumo]]></category>
            <dc:creator><![CDATA[Devon Fazekas]]></dc:creator>
            <pubDate>Sun, 21 Aug 2022 05:45:13 GMT</pubDate>
            <atom:updated>2022-08-23T12:28:04.222Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of contents</h3><p>- <a href="#1567">Introduction</a><br>- <a href="#3eec">Prerequisites</a><br>- <a href="#cca5">Getting started</a><br> — <a href="#75c4">Create the network</a><br> — <a href="#2cf4">Create traffic demand</a><br> — <a href="#e032">Optional visualization</a><br>- <a href="#d361">Running the simulation</a><br> — <a href="#e5e6">Start the simulation</a><br> — <a href="#3a92">Incrementing the simulation clock</a><br> — <a href="#4eed">Closing the simulation</a><br> — <a href="#fc58">Putting it all together</a><br> — <a href="#366e">Run the simulation</a><br>- <a href="#51e1">Introducing the detour</a><br> — <a href="#f0c4">Detour logic</a><br> — <a href="#851e">Applying logic to vehicles</a><br> — <a href="#b131">Change vehicle color</a><br> — <a href="#c7e7">Putting things together</a><br>- <a href="#8683">Final result</a></p><h3>Introduction</h3><p>This article will show you how to dynamically select vehicles to detour around specified roads within a SUMO traffic simulation.</p><p>Detours are a common event in urban driving and are caused by many reasons, including construction and vehicular accidents, to name a few. Whatever the reason, not all vehicles will choose to avoid these roads; some may drive straight through without a care, while others might take to the side streets. We will simulate both behaviours.</p><h3>Prerequisites</h3><p>I assume you have already installed SUMO on your machine and configured your <strong>PATH</strong> and <strong>SUMO_HOME</strong> environment variables. Read the <a href="https://sumo.dlr.de/docs/Basics/Basic_Computer_Skills.html">documentation</a> to learn how to get set up. To test that your machine is ready, you should be able to execute the following commands in a terminal:</p><ul><li>sumo --version</li><li>sumo-gui</li><li>python --version</li><li>netedit</li></ul><h3>Getting started</h3><p>If you’re familiar with SUMO traffic simulations or have read my other tutorials, then you might already know that the foundational components to run a simulation in SUMO include:</p><ul><li>a <strong>network</strong></li><li><strong>traffic demand</strong></li></ul><p>In SUMO, simulations are deterministic by default, but there are various ways to introduce randomness. For our purposes, we’ll leverage a tool called Traffic Control Interface (<strong>TraCI </strong>for short) provided by SUMO to allow modifying the simulation in real-time.</p><p><strong>TraCI</strong> enables us to introduce custom logic (in the form of Python code) to track and manipulate many aspects of the simulation, including the routes of individual vehicles. This article provides various source code examples to help you follow along. Three configuration files are grouped in a <em>config</em> folder, and one Python script — called <em>main.py</em> — contains all the logic to run and manipulate our simulation. To get started, mimic this folder structure on your machine.</p><figure><img alt="Screenshot of the project folder structure." src="https://cdn-images-1.medium.com/max/296/0*yAkUdFymIsUZDYKG" /><figcaption>Screenshot of the project folder structure.</figcaption></figure><h4>Create the network</h4><p>This section focuses on the network. The shape and complexity of the network are irrelevant. What matters is that you identify the name (id) of an edge you wish for the vehicles to avoid in the simulation. For the convenience of clarity, I’ll edit the network to rename three edges:</p><ul><li>the origin edge (as “origin”) where all vehicles will depart;</li><li>the destination edge (as “destination”) where all vehicles are destined;</li><li>and the edge some vehicles will avoid (as “closed”).</li></ul><blockquote>If you’re <strong><em>unfamiliar</em></strong><em> </em>with creating <strong>networks</strong>, check out my tutorial on <a href="https://medium.com/@fazekade/using-sumo-netedit-to-design-a-simple-network-4fdd4c3f1cc2">using <strong>netedit</strong> to design your own networks</a>.</blockquote><figure><img alt="Screenshot of the example network with custom-named edges highlighted for illustration purposes." src="https://cdn-images-1.medium.com/max/1024/0*N5JrLGSO48suxrt0" /><figcaption>Screenshot of the example network with custom-named edges highlighted for illustration purposes.</figcaption></figure><p>For those following along and wanting more practice in using <strong>netedit</strong>, I’ve provided two tables below for the lists of junctions and edges you can use as reference when recreating the example network.</p><p><strong>List of junctions</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d8212567155cf8032856251b7f58869/href">https://medium.com/media/8d8212567155cf8032856251b7f58869/href</a></iframe><p><strong>List of edges</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9735586ff163dd7cfc292aef7d1181e6/href">https://medium.com/media/9735586ff163dd7cfc292aef7d1181e6/href</a></iframe><p>For those who feel too lazy to draw their own networks, here is the source code for the example network shown above. Simply paste it into a file called <strong><em>network.net.xml</em></strong> in the <em>config</em> folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e69f6d58ed59240dab437395ce41e92/href">https://medium.com/media/6e69f6d58ed59240dab437395ce41e92/href</a></iframe><h4>Create traffic demand</h4><p>This section is about traffic demand, another foundational component for traffic simulations. For our purposes, we can keep things simple using a handful of identical vehicles initially following the same <strong>route</strong>. We’ll later introduce custom logic to modify these routes dynamically.</p><ul><li><strong>Route</strong> ⇒ an expanded <strong>trip</strong> including the origin and destination edges and all edges in between.</li><li><strong>Trip</strong> ⇒ a vehicular movement from one place to another.</li></ul><p>There are many ways to generate <strong>routes</strong> in SUMO, with the choice depending on your available inputs. For our needs, we know the origin and destination edges. Still, we can save time by leaving out the intermediate edges and allowing SUMO to figure out the best path. To learn more about demand modelling, read the <a href="https://sumo.dlr.de/docs/Demand/Introduction_to_demand_modelling_in_SUMO.html">documentation</a>.</p><p>With the example network, there are only two possible <strong>routes</strong> a vehicle can travel from origin to destination. In the figure below, these routes are illustrated with coloured arrows. By default, SUMO estimates travel time based on edge speed limits and distance, and it’ll choose the optimal path (aka. route) for individual vehicles to follow.</p><figure><img alt="Possible vehicular route configurations on the example network." src="https://cdn-images-1.medium.com/max/1024/0*0kfKdmC_dUEedhBt" /><figcaption>Possible vehicular route configurations on the example network.</figcaption></figure><p>Let’s start by describing our <strong>trips</strong>. Although it’s possible to configure traffic demand using tools like <strong>netedit</strong>, it’s much easier to write the source code directly in this instance. Start by creating a file in the <em>config</em> folder, and let’s name it <em>trips.trips.xml</em>.</p><p>The basic description of a <strong>trip</strong> requires only an identifier (id), the origin (from) and destination (to) edges, as well as the time when the vehicle enters the network (depart). As previously mentioned, we’re leveraging automatic routing to generate our <strong>routes</strong> during runtime. To learn more about automatic routing, check out the <a href="https://sumo.dlr.de/docs/Demand/Automatic_Routing.html">documentation</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0540fcc55052787037510e4588347a05/href">https://medium.com/media/0540fcc55052787037510e4588347a05/href</a></iframe><h4>Optional visualization</h4><p>By default, SUMO GUI uses the “<em>standard</em>” view setting, representing vehicles as triangles and colouring the network grey. I prefer to use the “<em>real world</em>” view setting, which, as the name suggests, adds a more realistic visual representation of the elements in the simulation.</p><p>With SUMO GUI open, you can switch between the available view settings, but to change the default when the application loads, the config file <em>viewSettings.xml</em> is required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/481f4fae0a55f00668ad10bb7bcb3229/href">https://medium.com/media/481f4fae0a55f00668ad10bb7bcb3229/href</a></iframe><h3>Running the simulation</h3><p>By this point, you should have a project structure that resembles the one shown in the introduction, with two (optionally three) configuration files in the <em>config</em> folder. What’s missing is the runner script that orchestrates the simulation — and later, the handling of our detouring logic. This section focuses on the runner script, so let’s get started!</p><p>At the very least, the runner script will initiate the simulation, move the clock forward, and close the simulation once all the vehicles have exited.</p><h4><strong>Start the simulation</strong></h4><p>To simply get the simulation to run, we need <strong>TraCI</strong> to pipe our <strong>network</strong> and <strong>trip</strong> files into <a href="https://sumo.dlr.de/docs/sumo-gui.html#:~:text=sumo%2Dgui%20is%20basically%20the,the%20same%20output%20as%20sumo"><strong>SUMO GUI</strong></a> (the graphical interface of SUMO). We’ll define a function, startSim(), to handle this operation. The following two procedures include moving the simulation time forward and also stopping the simulation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1fab764e7798e9dd78c6c4aa977266e/href">https://medium.com/media/b1fab764e7798e9dd78c6c4aa977266e/href</a></iframe><p>To use <strong>TraCI</strong>, we must provide it with a binary of an application and execution options. This binary will be <strong>SUMO-GUI</strong>, and we’ll obtain its binary using the checkBinary function in the <a href="https://sumo.dlr.de/docs/Tools/Sumolib.html">sumolib library</a>. The execution options depend on the application. For our purposes, we’re required to use the following options:</p><ul><li>--net-file [FILE] → Reads the <strong>network</strong> file.</li><li>--route-files [FILES] → Reads the <strong>routes/trips</strong> file.</li></ul><p>While the following options are optional:</p><ul><li>--delay [FLOAT] → Adds [FLOAT] delay between simulation steps, which we&#39;ll use to essentially slow it down so human eyes can watch.</li><li>--gui-settings-file [FILE] → Reads visualization settings from the file, which we&#39;ll use to apply the &quot;real world&quot; skin to the road and vehicles.</li><li>--start → Automatically starts the simulation once loaded, saving us the trouble of pressing the start button manually.</li></ul><blockquote>👉 To view the list of available execution options, it’s general practice to execute the application directly in a terminal, followed by the option --help.</blockquote><h4><strong>Incrementing the simulation clock</strong></h4><p>Without instructing TraCI when or how to increment the simulation clock, the simulation will remain frozen in time. We can easily increment the clock by calling the traci.simulationStep() method. However, this method only moves the clock by one second, so we’ll need to wrap this in a loop to continuously increment time.</p><p>To prevent the simulation from running forever, we’ll create a new function, shouldContinueSim(), to check if all the vehicles from our <strong>trips</strong> have entered and exited the network.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adaebdbc11fd7aadd44d34b1264dd748/href">https://medium.com/media/adaebdbc11fd7aadd44d34b1264dd748/href</a></iframe><h4><strong>Closing the simulation</strong></h4><p>And finally, to stop TraCI from running, we’ll use its traci.close() method.</p><h4><strong>Putting it all together</strong></h4><p>Let’s put everything together in the <em>main.py</em> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11e175f2c06de1bb7a587f3f3633839f/href">https://medium.com/media/11e175f2c06de1bb7a587f3f3633839f/href</a></iframe><h4><strong>Run the simulation</strong></h4><p>Let’s run the simulation. In the terminal, execute the runner script with the command python main.py. You’ll watch all our vehicles enter the network from the leftmost edge and drive their optimal routes towards the rightmost edge. Voila! Next, we’ll introduce the detour logic.</p><figure><img alt="GIF — Simulation of all vehicles driving the optimal route." src="https://cdn-images-1.medium.com/max/800/0*bBhDyZKJUoKaV__V" /><figcaption>GIF — Simulation of all vehicles driving the optimal route.</figcaption></figure><h3>Introducing the detour</h3><p>So we’ve got our simulation generating vehicles and their respective routes based on our trip descriptions. Now it’s time to introduce the detour logic. In this section, we’ll select a handful of vehicles to detour and change their colour to help visually distinguish them from the unaffected vehicles.</p><h4><strong>Detour logic</strong></h4><p>Our approach to deter our vehicle from driving through the specific edge is to tell the vehicle that its travel time through the edge would be infinitely large. This approach works if the routing algorithm used by SUMO considers travel time in its calculations (which it does by default). Each vehicle considers edge travel time individually, and to change its perspective of these estimated travel times, TraCI provides the traci.vehicle.setAdaptedTraveltime() method.</p><p>Changing a vehicle’s perspective of edge travel times does nothing on its own because the vehicle decided its route when it initially entered the network and will not automatically change it. We need to force it to recalculate its route using the traci.vehicle.rerouteTraveltime() method. Together, these two methods will convince the vehicle to choose an alternative route to avoid the targeted edges. We&#39;ll create a function, avoidEdge(), to handle this operation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04f96111b5761ba2278f4eaa5a865857/href">https://medium.com/media/04f96111b5761ba2278f4eaa5a865857/href</a></iframe><h4><strong>Applying logic to vehicles</strong></h4><p>Now that we have the logic, we need to select and apply it to vehicles and the edge to avoid.</p><p>There are many ways to select vehicles, but we’ll take the most straightforward approach and manually record the names from our <strong>trips</strong> file. Knowing the IDs of the vehicles and edge is required for this step. I’ll use a global variable array, VEHICLES, to contain the names of these vehicles and another variable, EDGE_ID, to contain the edge&#39;s name.</p><p>Unfortunately, SUMO may throw an error if you try to access specific vehicle properties while the vehicle is not on the network. So we need to ensure the vehicle exists before we try to change anything, but there is no direct way to do this. One technique is to check if its name is among the list of vehicles that entered the network during this time by using the traci.simulation.getDepartedIDList() method. We&#39;ll create a function, getOurDeparted(), to handle this operation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5db000ff19ce60ff8897a0f00732636/href">https://medium.com/media/f5db000ff19ce60ff8897a0f00732636/href</a></iframe><h4>Change vehicle color</h4><p>Next, but optional, is to change the colour of our vehicle to red using the traci.vehicle.setColor() method. This will help us visually identify it among the other vehicles. We&#39;ll create a function, setVehColor(), to handle this operation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bb7fed3a5faee20eb2e965519af7913/href">https://medium.com/media/7bb7fed3a5faee20eb2e965519af7913/href</a></iframe><h4><strong>Putting things together</strong></h4><p>With all the above components, we can start and stop the simulation, increment its clock, and change vehicle colour and routes. With these, your <em>main.py</em> file should look like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/473fb4ca3d4d657553f1643c6b69409f/href">https://medium.com/media/473fb4ca3d4d657553f1643c6b69409f/href</a></iframe><h3>Final result</h3><p>Suppose you run the simulation now (python main.py). In that case, you&#39;ll notice that the vehicles we previously selected appear red once they enter the network. Additionally, as they approach the first intersection, they&#39;ll slow down, signal and turn right down the side street. At the same time, all other yellow vehicles continue straight (or change lanes to avoid a collision).</p><p>You’ll recall that we did not specify any intermediate edges in the description of our <strong>trips</strong>; this is all handled by SUMO. In fact, this behaviour is dynamic and based on various aspects of the network and traffic. For instance, by adding more side streets or introducing traffic lights, the vehicles would likely choose separate routes to avoid causing traffic jams.</p><figure><img alt="GIF — Simulation of some vehicles driving the detoured route." src="https://cdn-images-1.medium.com/max/800/0*XufE3DeoZCBQmilG" /><figcaption>GIF — Simulation of some vehicles driving the detoured route.</figcaption></figure><p><strong>Congratulations!</strong> Through this article, you designed a network, described traffic demand, configured visualization settings, set up TraCI to manage the simulation, and introduced dynamic detouring logic.</p><blockquote>If you have any questions/suggestions, let’s connect on Github or LinkedIn!</blockquote><p><a href="https://github.com/DFazekas">https://github.com/DFazekas</a></p><p><a href="https://www.linkedin.com/in/devon-fazekas/">https://www.linkedin.com/in/devon-fazekas</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e57a50457dba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using SUMO netedit to design a simple network]]></title>
            <link>https://medium.com/@devonfazekas/using-sumo-netedit-to-design-a-simple-network-4fdd4c3f1cc2?source=rss-d80dcc5ba400------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fdd4c3f1cc2</guid>
            <category><![CDATA[traffic-simulation]]></category>
            <category><![CDATA[sumo]]></category>
            <category><![CDATA[netedit]]></category>
            <category><![CDATA[network-traffic]]></category>
            <dc:creator><![CDATA[Devon Fazekas]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 04:07:04 GMT</pubDate>
            <atom:updated>2022-08-23T12:05:07.711Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Table of contents</strong></h3><p>- <a href="#17d0">Introduction</a><br>- <a href="#e875">Prerequisites</a><br>- <a href="#635c">What is a network?</a><br> — <a href="#6d1e">Network file format</a><br> — <a href="#3bd2">netconvert</a><br> — <a href="#5a2b">netedit</a><br>- <a href="#50fd">Create a network file using netedit</a><br> — <a href="#5a9a">Draw the network</a><br> — <a href="#e186">Finetune the edges and junctions</a><br> — <a href="#f1d1">Saving the network</a><br>- <a href="#33a8">Final thoughts</a></p><h3>Introduction</h3><p>In this article, we’ll walk through using the netedit tool to design a simple <strong>network </strong>file for the <strong>SUMO </strong>ecosystem.</p><blockquote>This article is intended for <strong>beginners </strong>of SUMO and netedit, looking to learn the basics of drawing networks.</blockquote><h3>Prerequisites</h3><p>I assume you have already installed SUMO on your machine and configured your <strong>PATH</strong> and <strong>SUMO_HOME</strong> environment variables. Read the <a href="https://sumo.dlr.de/docs/Basics/Basic_Computer_Skills.html">documentation</a> to learn how to get set up. To test that your machine is ready, you should be able to execute the following commands in a terminal:</p><ul><li>sumo --version</li><li>sumo-gui</li><li>netedit</li></ul><h3>What is a network?</h3><blockquote>If you’re already familiar with the concepts of networks, skip to the section below titled “<a href="#50fd">Create a network file using netedit</a>”.</blockquote><p>According to official <a href="https://sumo.dlr.de/docs/Networks/SUMO_Road_Networks.html">documentation</a>, a SUMO network is a directed graph comprised of junctions and edges.</p><ul><li>“<strong>junction</strong>” (aka. “intersection” or “node”): A single point where at least one edge starts or ends.</li><li>“<strong>edge</strong>” (aka. “street”): A single-directed street connection between two junctions, and containing at least one lane.</li></ul><h4>Network file format</h4><p>For SUMO, networks can get quite large and complex, so it’s best practice to group their components together in a single file, called a <strong>network file</strong> (<em>who would have guess?</em>). A <strong>network file</strong> can be of two formats:</p><ul><li>a set of <strong><em>plain-xml</em></strong> files describing the network topology and geometry.</li><li>the<strong> <em>.net.xml</em></strong> file used by the simulation, containing lots of generated information.</li></ul><blockquote>Only the <strong><em>plain-xml</em></strong> format is meant to be edited by the users.</blockquote><p>Regardless of which format you have or want, SUMO provides tools to work and convert between them. The two most relevant tools include <strong>netconvert</strong> and <strong>netedit</strong>.</p><h4>netconvert</h4><p>netconvert is a <strong>command line application</strong> included in SUMO that generates road networks from different sources. Read the <a href="https://sumo.dlr.de/docs/netconvert.html">documentation</a> to learn more about its usage. netconvert can convert between both network formats without information loss.</p><h4>netedit</h4><p>netedit is a <strong>graphical network editor</strong> included in SUMO and built on top of netconvert. Read the <a href="https://sumo.dlr.de/docs/Netedit/index.html">documentation</a> to learn more of its usage.</p><h3>Create a network file using netedit</h3><p>In this section, we’ll walk through the process of using netedit to generate a <strong>network file</strong>. As previously mentioned, a network is a directed graph of junctions with edges connecting them.</p><p>The design of the network we’re creating is simple, as shown below. In fact, it’s an unrealistically simple network containing only <strong>11 junctions</strong> and <strong>14 edges</strong>.</p><figure><img alt="Screenshot of a network viewed in netedit." src="https://cdn-images-1.medium.com/max/1024/1*Iu8V5XL5he4PPEzJkB_1Gw.png" /><figcaption>Screenshot of the <strong>network </strong>viewed in netedit.</figcaption></figure><p>To reduce any guesswork in following along with the above network design, the below tables list all the relevant junction and edge info needed. We’ll refer back to these tables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25d090e6c0aeb14d89386a70653f52f7/href">https://medium.com/media/25d090e6c0aeb14d89386a70653f52f7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a75a99398703c30c4f743ad7abad633b/href">https://medium.com/media/a75a99398703c30c4f743ad7abad633b/href</a></iframe><h4>Draw the network</h4><p>You’re now ready to start using netedit to design a network and ultimately generate a network file. Let’s get started!</p><p>First, open netedit from a command line using the command netedit. Immediately create a new network with the <em>File &gt;</em> select “<em>New Network</em>” button. This will provide you with a blank canvas for drawing the network.</p><p>We’ll start with placing the <strong>junctions </strong>on the canvas. In netedit, creating two <strong>junctions </strong>automatically generates the connecting <strong>edge </strong>(<em>cool!</em>). Read the <a href="https://sumo.dlr.de/docs/Netedit/editModesNetwork.html#create_edges">documentation</a> to learn more about creating edges in netedit. To create an edge, enter <strong><em>edge mode</em></strong> by hitting the [e] key or clicking its button in the control panel.</p><figure><img alt="Entering Edge Mode in netedit to create a rectangular network." src="https://cdn-images-1.medium.com/max/800/1*uZOe2knfrQz9kHW7iCqhCA.gif" /><figcaption>Entering <strong>Edge Mode</strong> in netedit to create a rectangular network.</figcaption></figure><p>For convenience, turn on <strong><em>edge chain mode</em></strong> to allow chaining multiple edges without interruptions and <strong><em>show grid</em></strong> (<em>not shown here, sorry!</em>) to help with placement. At this point, you can randomly place all of our junctions as we’ll finetune their positions and other attributes in the next steps.</p><h4>Finetune the edges and junctions</h4><p>So you’ve placed all your edges/junctions on the canvas. Great! Now is the time to finetune and adjust their attributes.</p><p>To view attributes, you first must enter <strong><em>inspect mode</em> </strong>by hitting the [i] key or clicking its button in the control panel.</p><p>When clicking on any element on the canvas, its attributes display on the left panel. There are many customizable attributes for each type of element. For our purposes, we only care about a few. Specifically, for <strong>edges</strong>, we’ll rename their id if necessary, and set numLanes according to the tables above. Although the from and to attributes are relevant, netedit automatically syncs them to the connected junctions.</p><figure><img alt="Increasing number of edge lanes using netedit." src="https://cdn-images-1.medium.com/max/800/1*eFIl5XKAtASuyH2Kst83vg.gif" /><figcaption>Increasing number of edge lanes using netedit.</figcaption></figure><p>For <strong>junctions</strong>, we’ll also rename their id if necessary, and change their pos according to the tables above.</p><figure><img alt="Changing junction position using netedit." src="https://cdn-images-1.medium.com/max/800/1*ZwWpZiHb_MV83NV8RuZvng.gif" /><figcaption>Changing junction position using netedit.</figcaption></figure><h4>Saving the network</h4><p>If the attributes of your edges and junctions match the tables above, then your network should look like the designs from earlier. In that case, your network is now complete!</p><p><strong>Save your network</strong> by hitting the [<em>CTRL + s</em>] key or pressing the <em>File &gt; </em>“<em>Save Network As…</em>” button. While a network file must have a “<em>.net.xml</em>” extension, the name can be virtually anything. I suggest naming the file something relevant such as “<em>network.net.xml</em>”.</p><h3>Final thoughts</h3><p>In this article, you learned the basics of network formats, some tools for designing and modifying networks, and got hands-on experience in creating your own network file.</p><p>If you’re interested in applying what you’ve learned, check out my other tutorials.</p><blockquote>If you have any questions/suggestions, let’s connect on Github or LinkedIn!</blockquote><p><a href="https://github.com/DFazekas">https://github.com/DFazekas</a></p><p><a href="https://www.linkedin.com/in/devon-fazekas/">https://www.linkedin.com/in/devon-fazekas</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fdd4c3f1cc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>