{"componentChunkName":"component---src-templates-blog-post-js","path":"/posts/particlepostgetwebhk/","result":{"data":{"markdownRemark":{"html":"<p>Shameful plug post, but I'll be using Particle devices to demonstrate how to setup a Post/Get/Webhook right on a Google Sheet. Although Excel has more spreadsheet features than Google Sheets, the nice thing is that since your google sheets resides on some server connected to the internet, you can essentially use Google Sheets as a basic server to receive and send requests to an IoT device somewhere else. Take a look at how simple this spreadsheet is:</p>\n<p><img src=\"https://raw.githubusercontent.com/simjxu/simjxu.github.io/gh-pages/img/googlesht-getpostwebhk.jpg\" alt=\"googsht-GPW\"></p>\n<p>All requests will operate under a request/response format, the idea being that the Google Sheet I made will shoot off a request, and a response will be collected. ONE IMPORTANT NOTE: Since you will be allowing anonymous access in order to use Google Apps Script, PLEASE only use this for development testing purposes ONLY, not to run a production server. If someone finds your Google Sheets URL endpoint, they can flood your sheet with requests. Furthermore, your device access token may be exposed.</p>\n<p>With that said, let's get started.</p>\n<p>First you will want to create a new Google sheet which looks like what I've shown above. You can ignore cells B3, C3, and D2-D3, as these will be populated automatically by the webapp you'll create using Google Apps Script. You don't have to do this, but I merged cell D2 and D3. To create the buttons, go to Insert >> Drawing to draw a basic rectangle with some text in the middle. You will be able to assign function to these buttons you created later.</p>\n<p>Particle (www.particle.io) makes it easy for you connect sensors to the internet. I'm using a Particle Photon in this example, but you can use whatever you want. Take a look at docs.particle.io to get your Photon up and running. From the starter kit, you can set up your resistors, LED, and photoresistor like I did in the below image:</p>\n<p><img src=\"https://raw.githubusercontent.com/simjxu/simjxu.github.io/gh-pages/img/particle-photon.JPG\" alt=\"photon-pic\"></p>\n<p>You will need to flash a binary to the Photon that sets it up to receive function calls and publish variables and events. You can how I did that in this script: <a href=\"https://github.com/simjxu/partiscripts/blob/master/getpostwebhook-example/photoresistor.ino\">https://github.com/simjxu/partiscripts/blob/master/getpostwebhook-example/photoresistor.ino</a> </p>\n<p>In my <code>setup()</code> section I've called out 3 different <code>Particle.variables</code>: <code>analogvalue</code>, which is the output from the photoresistor, <code>brightness</code>, which is the brightness of the LED, and <code>setpoint</code>, which is the setpoint issued to the LED. I've also created a <code>Particle.function</code> called <code>led</code>, which toggles the blue LED situated on D7 on the board. Lastly, I've created a <code>Particle.publish</code>, which tracks the analog value and publishes a <code>low_light</code> event when the value drops below 50. </p>\n<p>What I will do now is use my \"Post Request\" function on my google sheet to call the <code>led</code> function and toggle on/off the LED. I will use the \"Get Request\" button to pull the <code>analogvalue</code> variable. Lastly, I will create a webhook to publish the <code>low_light</code> event details to my Google sheet when the event publishes.</p>\n<p>First, go to the Google Sheet and go to Tools >> Script Editor. This will allow you write javascript which controls how your Google Sheet behaves. Start off in the script by setting some Global variables. You have to retrieve you access token from build.particle.io, by clicking the settings tab. The device id is the device of your photon, and spreadsheet id is the long string of in your Google Sheets URL. You can also edit the Sheet name if you decide to change that.</p>\n<pre><code class=\"language-javascript\">// Set Global Variables \n/* \nACCESS_TOKEN: Go to build.particle.io and click \"Settings\" on the left side panel\nPARTICLE_DEVICE_ID: Identify device ID from the console, or from using \"particle list\"\nSPREADSHEET_ID: Look on the URL for your Google Sheet for the long random string\n*/\nPropertiesService.getScriptProperties().setProperty('SHEET_NAME', 'Sheet1');\nPropertiesService.getScriptProperties().setProperty('PARTICLE_ACCESS_TOKEN', '&#x3C;enter access token>');\nPropertiesService.getScriptProperties().setProperty('PARTICLE_DEVICE_ID', '&#x3C;enter device id>');\nPropertiesService.getScriptProperties().setProperty('SPREADSHEET_ID', '&#x3C;enter spreadsheetid>');\n</code></pre>\n<p>Handling the Post Request:\nGo back to your Google Sheet, and right click the button you labeled \"MAKE POST REQUEST\", and assign it a function called <code>PostRequest</code> or whatever you decide to name it. In the script file, add the function below. You will be using the Particle API URL, and sending the request there. The request will require your access token, and the argument (in the case above, either \"on\" or \"off\" for the LED).</p>\n<pre><code class=\"language-javascript\">// Handle the button click for Post Request -------------------------------------------------\nfunction PostRequest() {\n  var spreadsheet_id = SpreadsheetApp.getActiveSpreadsheet().getId();\n  var sheet = SpreadsheetApp.openById(spreadsheet_id).getSheetByName( \n    PropertiesService.getScriptProperties().getProperty('SHEET_NAME'));\n  \n  // API url goes like this:\n  // https://api.particle.io/v1/devices/&#x3C;deviceid>/\n  // led?args=on&#x26;access_token=&#x3C;accesstoken>\n  var device_id = PropertiesService.getScriptProperties().getProperty('PARTICLE_DEVICE_ID');\n  var access_token = PropertiesService.getScriptProperties().getProperty('PARTICLE_ACCESS_TOKEN');\n  var function_name = sheet.getRange(\"B4\").getValue();\n  var request = sheet.getRange(\"B2\").getValue();\n  var url = \"https://api.particle.io/v1/devices/\" + device_id + \"/\" + function_name + \"?\" + \n    \"access_token=\" + access_token;\n\n  // Create a form which will be sent as the payload to the post request\n  var formData = {\n    'args' : request\n    \n  };\n  \n  // Create the options\n  var options =\n      {\n        \"method\"  : \"POST\", \n        \"payload\"  : formData,\n        \"followRedirects\" : true,\n        \"muteHttpExceptions\": false\n      };\n  \n  // Send Post request body to the URL indicated\n  var result = UrlFetchApp.fetch(url, options);\n  \n  // Display response in Cell\n  if (result.getResponseCode() == 200) {  \n    var params = JSON.parse(result.getContentText());\n    sheet.getRange(\"B3\").setValue(params);\n  }\n}\n</code></pre>\n<p>The Get request is even simpler, as now you don't have to include a form as part of the package to be delivered. Don't forget to assign the function to the \"MAKE GET REQUEST\" button.</p>\n<pre><code class=\"language-javascript\">// Handle the button click for Get Request -------------------------------------------------\nfunction GetRequest() {\n  // Start by trying in postman\n  \n  // Set which spreadsheet to pull or output information\n  var spreadsheet_id = SpreadsheetApp.getActiveSpreadsheet().getId();\n  var sheet = SpreadsheetApp.openById(spreadsheet_id).getSheetByName( \n    PropertiesService.getScriptProperties().getProperty('SHEET_NAME'));\n  \n  // API url goes like this: \n  // https://api.particle.io/v1/devices/&#x3C;PARTICLE_DEVICE_ID>/&#x3C;VARIABLE_NAME>?access_token=&#x3C;PARTICLE_ACCESS_TOKEN>\n  var device_id = PropertiesService.getScriptProperties().getProperty('PARTICLE_DEVICE_ID');\n  var access_token = PropertiesService.getScriptProperties().getProperty('PARTICLE_ACCESS_TOKEN');\n  var variable_name = sheet.getRange(\"C2\").getValue();\n  var url = \"https://api.particle.io/v1/devices/\" + device_id + \"/\" + variable_name + \"?access_token=\" + access_token\n  \n  // Not sure if all options are necessary\n  var options =\n      {\n        \"method\"  : \"GET\",   \n        \"followRedirects\" : true,\n        \"muteHttpExceptions\": true\n      };\n  \n  // Send Get request body to the URL indicated\n  var result = UrlFetchApp.fetch(url, options);\n  \n  // Display response in Cell\n  if (result.getResponseCode() == 200) {\n    var params = JSON.parse(result.getContentText());\n    sheet.getRange(\"C3\").setValue(params);\n  };\n}\n</code></pre>\n<p>Finally, the Webhook. We need to set up the Google Sheet to be able to receive a message that is published to it. This is done through a function called <code>doPost()</code>. You will not be able to use any name you want, because doPost will be the handler to a post made externally.</p>\n<pre><code class=\"language-javascript\">// Handle the webhook using doPost() -------------------------------------------------\nfunction doPost(e){\n  // Set which spreadsheet to output this data to\n  var spreadsheet_id = PropertiesService.getScriptProperties().getProperty('SPREADSHEET_ID');\n  var sheet = SpreadsheetApp.openById(spreadsheet_id).getSheetByName( \n    PropertiesService.getScriptProperties().getProperty('SHEET_NAME'));\n  \n  // Fill the \"Webhook Data\" cell with the parameters of the webhook package sent\n  sheet.getRange(\"D2\").setValue(e.parameter);\n  \n  return ContentService.createTextOutput(JSON.stringify({text:\"webhook received\"})).setMimeType(ContentService.MimeType.JSON);;\n}\n</code></pre>\n<p>Once the full script is complete (full script available here, you will need to edit the Global variables section at the top: <a href=\"https://github.com/simjxu/partiscripts/blob/master/getpostwebhook-example/googlesheets_pgw.gs\">https://github.com/simjxu/partiscripts/blob/master/getpostwebhook-example/googlesheets_pgw.gs</a>)go to your Google Apps script (<a href=\"https://script.google.com...\">https://script.google.com...</a>), and select Publish >> Deploy as webapp. Copy the webapp URL, which you will need to setup the webhook on the Particle console. Then in the section that says \"Who has access to the app\", you will need to select \"Anyone, even anonymous\". This will ensure that the Particle console can make changes to the google sheet.\nThe webhook must also be set up as an integration on console.particle.io. with a Web Form setup. </p>\n<p><img src=\"https://raw.githubusercontent.com/simjxu/simjxu.github.io/gh-pages/img/webhooksetupconsole.jpg\" alt=\"webhook-console\"></p>\n<p>Under the Full URL section, you will need to include the target URL for your google sheets webapp. It should begin with <a href=\"https://script.google.com/..\">https://script.google.com/..</a>. This is the URL you copied earlier after deploying as a webapp.</p>\n<p>That's it! Now you have a Google sheet with a webapp that will communicate between the sheet and your Particle IoT device. Try changing the Post Request section (B2) to \"on\" or \"off\" and clicking the \"MAKE POST REQUEST\" button. Try changing cell C2 to brightness, or setpoint, and clicking \"MAKE GET REQUEST\" to view the values. Try holding your hand over the photoresistor on the photoresistor to block out enough light to trigger the webhook event.</p>","frontmatter":{"title":"How to use Google Sheets as a Post/Get/Webhook Endpoint"}}},"pageContext":{"slug":"/posts/particlepostgetwebhk/"}},"staticQueryHashes":["3649515864"]}