iot.exec.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //IoT Scanner
  2. //This agi script will list the manager cached device list. If the list not exists
  3. //It will perform an auto scan instead.
  4. //Require the iot lib
  5. requirelib("iot");
  6. function main(){
  7. //Check if the IoT Controller is ready
  8. if (iot.ready() == true){
  9. //List the iot device in cache
  10. var deviceList = iot.list();
  11. if (deviceList.length == 0){
  12. sendResp("No iot device found");
  13. return;
  14. }
  15. //Assuming the first device is an example object with a basic echo function
  16. //When an AJAX request is called to its endpoint
  17. var thisDevice = deviceList[0]; //Change this if your testing device is not the first device on the iot device list
  18. console.log(thisDevice.Name);
  19. //Connect the first device by its uuid
  20. iot.connect(thisDevice.DeviceUUID);
  21. //Find the endpoint with type "none"
  22. var targetEndpoint = undefined;
  23. for (var i = 0; i < thisDevice.ControlEndpoints.length; i++){
  24. var thisEndpoint = thisDevice.ControlEndpoints[i];
  25. if (thisEndpoint.Type == "none"){
  26. //Lets pick this endpoint as an example for toggling
  27. targetEndpoint = thisEndpoint;
  28. break;
  29. }
  30. }
  31. if (targetEndpoint == undefined){
  32. sendResp("This device do not have an endpoint with type \"none\". Try again with another iot device in your network.")
  33. return
  34. }
  35. //Now, we execute this endpoint by the device id and the endpoint name
  36. //exec require {device id, target endppoint name, payload (object)}
  37. //In this case, we can pass anything into the object field as none type endpoint
  38. //will just ignore all the input payload
  39. var results = iot.exec(thisDevice.DeviceUUID, targetEndpoint.Name, {})
  40. //Disconnect the iot device if needed
  41. iot.disconnect(thisDevice.DeviceUUID);
  42. if (results == false){
  43. //There is something wrong with the toggling. See Terminal for output
  44. sendResp("Failed to toggle device. See terminal for more information.")
  45. }else{
  46. //Return what the iot device reply to the responce output
  47. //The results return from iot.exec is an JSON object
  48. HTTP_HEADER = "application/json; charset=utf-8";
  49. sendResp(JSON.stringify(results));
  50. }
  51. }else{
  52. sendResp("IoT Manager not ready");
  53. }
  54. }
  55. //Run the main function
  56. main();