1+ import * as dgram from 'dgram' ;
2+ import * as qrcode from 'qrcode-terminal' ;
13import {
24 CommandLineInputs ,
35 CommandLineOptions ,
@@ -79,6 +81,11 @@ import {
7981 name : 'platform' ,
8082 description : 'Start serve with a specific platform (ios/android)' ,
8183 aliases : [ 't' ]
84+ } ,
85+ {
86+ name : 'qrcode' ,
87+ description : 'Print a QR code for Ionic View instead of network broadcasting' ,
88+ type : Boolean
8289 }
8390 ] ,
8491 requiresProject : true
@@ -90,13 +97,61 @@ export class ServeCommand extends Command {
9097
9198 var tasks = new TaskChain ( ) ;
9299
93- await this . env . emitEvent ( 'serve' , {
100+ var response = await this . env . emitEvent ( 'serve' , {
94101 metadata : this . metadata ,
95102 inputs,
96103 options
97104 } ) ;
98105
99106 tasks . next ( `Starting server` ) ;
107+
108+ // If qrcode option then generate a qrcode on the Command Line.
109+ if ( options . qrcode ) {
110+ const codeString = await generateQrCode (
111+ `${ response . protocol } ://${ response . publicIp } :${ response . httpPort } `
112+ ) ;
113+ this . env . log . msg ( `\n\n\n${ codeString } ` ) ;
114+ }
115+
116+ // If broadcast option then start udp server and broadcast info
117+ if ( options . broadcast ) {
118+ tasks . next ( `Broadcasting server information` ) ;
119+ const appDetails = await this . env . project . load ( ) ;
120+
121+ const message = JSON . stringify ( {
122+ app_name : appDetails . name ,
123+ app_id : appDetails . app_id ,
124+ local_address : `${ response . protocol } ://${ response . publicIp } :${ response . httpPort } `
125+ } ) ;
126+ const server = dgram . createSocket ( 'udp4' ) ;
127+
128+ server . on ( 'listening' , ( ) => {
129+ server . setBroadcast ( true ) ;
130+ setInterval ( ( ) => {
131+ try {
132+ server . send ( message , 41234 , '255.255.255.255' ) ;
133+ } catch ( e ) {
134+ throw e ;
135+ }
136+ } , 3000 ) ;
137+ } ) ;
138+
139+ server . bind ( ) ;
140+ }
141+
100142 tasks . end ( ) ;
101143 }
102144}
145+
146+ function generateQrCode ( input : string ) : Promise < string > {
147+ return new Promise ( ( resolve , reject ) => {
148+
149+ try {
150+ qrcode . generate ( input , ( response : any ) => {
151+ resolve ( response ) ;
152+ } ) ;
153+ } catch ( e ) {
154+ reject ( e ) ;
155+ }
156+ } ) ;
157+ }
0 commit comments