How to send udp packet


#1

Hello. I have two buttons. I want to send a certain message when a certain button is pressed. I try to send a packet like this

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
    
    chrome.socket.create('udp', '192.168.1.129', 2390, {},
     function(socketInfo) {
       // The socket is created, now we want to connect to the service
       var socketId = socketInfo.socketId;
       chrome.socket.connect(socketId, function(result) {
         // We are now connected to the socket so send it some data
         chrome.socket.write(socketId, arrayBuffer,
           function(sendInfo) {
             console.log("wrote " + sendInfo.bytesWritten);
           }
         );
       });
     }
    );

  });
})

The button is not connected (I don’t know how to do it); I get this error on the chrome.socket.create line:

Uncaught TypeError: Cannot read property 'create' of undefined

Further attempts:
I tried connecting the buttons like this

html

<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <body ng-app="starter">

    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">key</h1>
      </ion-header-bar>
      <ion-content>
        <button class="button button-block button-balanced" ng-click="sendcmd('l')">
          lock
        </button>
        <button class="button button-block button-assertive" ng-click="sendcmd('u')">
          unlock
        </button>
      </ion-content>
    </ion-pane>
  </body>
</html>



js

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

function sendcmd(cmd) {
  console.log("cmd: ");
  console.log(cmd);
  console.log(".\n");

  chrome.socket.create('udp', '192.168.1.129', 2390, {},
   function(socketInfo) {
     // The socket is created, now we want to connect to the service
     var socketId = socketInfo.socketId;
     chrome.socket.connect(socketId, function(result) {
       // We are now connected to the socket so send it some data
       chrome.socket.write(socketId, cmd,
         function(sendInfo) {
           console.log("wrote " + sendInfo.bytesWritten);
         }
       );
     });
   }
  );
}

```
I don't get any presses logged in the console.  
 
update:
button works like this:
```
angular.module('key', ['ionic'])
.controller('keyctrl', function($scope) {
  $scope.sendcmd = function(cmd) {
    console.log("cmd: " + cmd);*/
  }
});
```

UDP connection example in ionic?
#2

Okay, now I have the buttons wired up

angular.module('key', ['ionic'])
.controller('keyctrl', function($scope) {
  $scope.sendcmd = function sendcmd(cmd) {
    console.log("cmd: " + cmd);
    chrome.socket.udp('udp', '192.168.1.129', 2390, {},
     function(socketInfo) {
       // The socket is created, now we want to connect to the service
       var socketId = socketInfo.socketId;
       chrome.socket.connect(socketId, function(result) {
         // We are now connected to the socket so send it some data
         chrome.socket.write(socketId, cmd,
           function(sendInfo) {
             console.log("wrote " + sendInfo.bytesWritten);
           }
         );
       });
     }
    );

  };
});

(tips on avoiding indentation accepted)
on click:

TypeError: Cannot read property 'create' of undefined
    at Scope.sendcmd (http://localhost:8100/js/app.js:23:18)
    at fn (eval at <anonymous> (http://localhost:8100/lib/ionic/js/ionic.bundle.js:21972:15), <anonymous>:4:222)
    at http://localhost:8100/lib/ionic/js/ionic.bundle.js:57514:9
    at Scope.parent.$get.Scope.$eval (http://localhost:8100/lib/ionic/js/ionic.bundle.js:24673:28)
    at Scope.parent.$get.Scope.$apply (http://localhost:8100/lib/ionic/js/ionic.bundle.js:24772:23)
    at HTMLButtonElement.<anonymous> (http://localhost:8100/lib/ionic/js/ionic.bundle.js:57513:13)
    at HTMLButtonElement.eventHandler (http://localhost:8100/lib/ionic/js/ionic.bundle.js:12098:21)
    at triggerMouseEvent (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2865:7)
    at tapClick (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2854:3)
    at HTMLDocument.tapTouchEnd (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2977:5)(anonymous function) @ ionic.bundle.js:21157ident.$get @ ionic.bundle.js:17936parent.$get.Scope.$apply @ ionic.bundle.js:24774(anonymous function) @ ionic.bundle.js:57513eventHandler @ ionic.bundle.js:12098triggerMouseEvent @ ionic.bundle.js:2865tapClick @ ionic.bundle.js:2854tapTouchEnd @ ionic.bundle.js:2977

#3

Hello,

Did you found solution for your error?

BR,
saurabh


#4

@drivingtheproject
No, I did not. I wrote it in android. There are a couple things to note. I had to run it on a phone to get a bit further. When I did and listed the plugins I only saw one. Here is a discussion where someone got it working for himself but I didn’t get it. https://github.com/MobileChromeApps/cordova-plugin-chrome-apps-sockets-udp/issues/5
Here is the test code which lists plugins https://github.com/jnsat/lock/blob/master/ionic/key/www/js/app.js


#5

Hi,

a bit late maybe, but this is how I got UDP going to discover SONOS through UPNP. I used cordova-plugin-chrome-apps-sockets-udp. (ionic 2)

Code:

declare var chrome;

	let PORT = 1900;

	// convert string to ArrayBuffer - taken from Chrome Developer page
	function str2ab(str) {
		var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
		var bufView = new Uint16Array(buf);
		for (var i = 0, strLen = str.length; i < strLen; i++) {
			bufView[i] = str.charCodeAt(i);
		}
		return buf;
	}

	// register the listeners.
	chrome.sockets.udp.onReceive.addListener(
		(info) => {
			console.log('Recv from socket: ',info);

			//chrome.sockets.udp.close(info.socketId);  // enable if only 1 IP needed
		}
	);

	chrome.sockets.udp.onReceiveError.addListener(
		(error) => {
			console.log('Recv  ERROR from socket: ', error);
			chrome.sockets.udp.close(error.socketId);
		}
	);

	// String to search for SONOS
	let SONOS_SEARCHSTRING = 'M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: ssdp:discover\r\nMX: 1\r\nST: urn:schemas-upnp-org:device:ZonePlayer:1';
	let UPNPALL_SEARCHSTRING = "M-SEARCH * HTTP/1.1\r\nHost: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 5\r\nST: ssdp:all\r\n\r\n";
	let UPNPROOTDEVICE_SEARCHSTRING = "M-SEARCH * HTTP/1.1\r\nHost: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 5\r\nST: upnp:rootdevice\r\n\r\n";

	// translate the string into ArrayBuffer
	let UPNPSTRING = str2ab(SONOS_SEARCHSTRING);

	// send  the UDP search as captures in UPNPSTRING and to port PORT, taken from plugin help text
	chrome.sockets.udp.create((createInfo) => {
		chrome.sockets.udp.bind(createInfo.socketId, '0.0.0.0', PORT, (bindresult) => {
			chrome.sockets.udp.setMulticastTimeToLive(createInfo.socketId, 2, (ttlresult) => {
				chrome.sockets.udp.setBroadcast(createInfo.socketId, true, function(sbresult) {
					chrome.sockets.udp.send(createInfo.socketId, UPNPSTRING, '239.255.255.250', PORT, (sendresult) => {
						if (sendresult < 0) {
							console.log('send fail: ' + sendresult);
						} else {
							console.log('sendTo: success ' + PORT, createInfo, bindresult, ttlresult, sbresult, sendresult);
						}
					});
				});
			});
		});
	});

#6

Long time since I worked on this code