Exemplo n.º 1
0
        public async void ReceiveFile()
        {
            if (BluetoothRadio.IsSupported)
            {
                if (numReceiving < 6)
                {
                    statusDisplay.Text = (++numReceiving).ToString();
                    BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
                    await Task.Run(() => {
                        ObexListener listener = new ObexListener(ObexTransport.Bluetooth);
                        listener.Start();
                        ObexListenerContext context = listener.GetContext();
                        ObexListenerRequest request = context.Request;
                        string[] pathSplits         = request.RawUrl.Split('/');
                        string fileName             = pathSplits[pathSplits.Length - 1];
                        request.WriteFile(filePath + fileName);
                        listener.Stop();
                        listener.Close();
                    });

                    statusDisplay.Text = (--numReceiving).ToString();
                }
                else
                {
                    MessageBox.Show("Number of pending transfers is limited to 6", "FYI", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            else
            {
                MessageBox.Show("Bluetooth must be enabled on your device for this function to work", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 2
0
 private void DealWithRequest()
 {
     while (mObexListener.IsListening)
     {
         try
         {
             ObexListenerContext olc = mObexListener.GetContext();
             ObexListenerRequest olr = olc.Request;
             string filename         = Uri.UnescapeDataString(olr.RawUrl.TrimStart(new char[] { '/' }));
             // olr.WriteFile(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\" + DateTime.Now.ToString("yyMMddHHmmss") + " " + filename);
             olr.WriteFile(Environment.SpecialFolder.MyDocuments + DateTime.Now.ToString("yyMMddHHmmss") + " " + filename);
             // olr.WriteFile("\\My Documents\\" + DateTime.Now.ToString("yyMMddHHmmss") + " " + filename);
             // 匿名方法 (Anonymous Method)
             // 匿名方法要求參數的是一個委託(delegate)類型, 編譯器在處理匿名方法的時候, 需要指定這個匿名方法將會返回什麼類型的委託, MethodInvoke和Action都是方法返回類型為空的委託
             BeginInvoke(new MethodInvoker(delegate()
             {
                 UpdateBTDeviceDetails("Received file : " + filename + "\r\nFolder Path :" + System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
             }));
         }
         catch (Exception ex)
         {
             BeginInvoke(new MethodInvoker(delegate() { UpdateBTDeviceDetails(ex.Message); }));
             continue;
         }
     }
 }
Exemplo n.º 3
0
        void Foo(ObexListener lsnr)
        {
            ObexListenerContext ctx = lsnr.GetContext();

            if (ctx != null)
            {
                ObexListenerRequest req = ctx.Request;
            }
        }
Exemplo n.º 4
0
        public void UnknownVerbNotSupport()
        {
            byte[]              requests          = NewWholeProcessTests_Data.SimpleUnknownVerb_ExpectedRequests;
            byte[]              expectedResponses = SimpleGet1_Responses_NotImplemented;
            Exception           ex;
            ObexListenerContext ctx = DoTest(requests, expectedResponses, true, out ex);

            //
            // We check above that we get error codes from the server.
            // We also want the user to know that the client didn't do a PUT.
            Assert.IsAssignableFrom(typeof(ProtocolViolationException), ex);
            Assert.AreEqual("No PutFinal received.", ex.Message);
        }
Exemplo n.º 5
0
 static private void listen()
 {
     while (true)
     {
         var listener = new ObexListener(ObexTransport.Bluetooth);
         listener.Start();
         ObexListenerContext con        = listener.GetContext();
         ObexListenerRequest req        = con.Request;
         String[]            pathSplits = req.RawUrl.Split('/');
         String filename = pathSplits[pathSplits.Length - 1];
         req.WriteFile(filename);
         listener.Stop();
     }
 }
Exemplo n.º 6
0
        private void buttonReceive_Click(object sender, EventArgs e)
        {
            ObexListener listener = new ObexListener();

            listener.Start();
            ObexListenerContext context = listener.GetContext();
            ObexListenerRequest request = context.Request;

            String[] pathSplits = request.RawUrl.Split('/');
            String   filename   = pathSplits[pathSplits.Length - 1];

            request.WriteFile(filename);
            listener.Stop();
        }
Exemplo n.º 7
0
        public void TwoPuts_SecondIsDisallowed()
        {
            byte[] requests          = NewWholeProcessTests_Data.TwoPuts_ExpectedRequests;
            byte[] expectedResponses = TwoPuts_DisallowFirstAndCloses_Responses;
            //
            ObexListenerContext ctx = DoTest(requests, expectedResponses);

            AssertHeader(ctx, "NAME", "aaaa.txt");
            AssertHeader(ctx, "LENGTH", "4");
            //
            Stream content = new MemoryStream();

            Stream_CopyTo(ctx.Request.InputStream, content);
            Assert.AreEqual(4, content.Length, "content.Length");
        }
Exemplo n.º 8
0
 // Funkcja pozwalająca na odbieranie plików
 private void ReceiveFiles()
 {
     while (isPaired)
     {
         var listener = new ObexListener(ObexTransport.Bluetooth);
         listener.Start();
         ObexListenerContext ctx        = listener.GetContext();
         ObexListenerRequest req        = ctx.Request;
         String[]            pathSplits = req.RawUrl.Split('/');
         String file = pathSplits[pathSplits.Length - 1];
         req.WriteFile(file);
         textBoxConsole.Text += "Odebrano plik.\r\n";
         listener.Stop();
     }
 }
Exemplo n.º 9
0
        public void WidcommMruxxB8()
        {
            byte[] requests          = SimplePut1_ExpectedRequests_WidcommMru0FB8;
            byte[] expectedResponses = SimplePut1_Responses;
            //
            MemoryStream peerRequests_ = new MemoryStream(requests, false);
            Stream       peerRequests  = ModifyReadStream(peerRequests_);
            MemoryStream ourResponses  = new MemoryStream();
            TwoWayStream peer          = new TwoWayStream(peerRequests, ourResponses);
            //
            SocketAdapter       s   = CreateSocketAdapter(peer);
            ObexListenerContext ctx = new ObexListenerContext(s);

            //
            Assert.AreEqual(expectedResponses, ourResponses.ToArray(), "ourResponses");
        }
Exemplo n.º 10
0
        void ObexSvr1()
        {
            var lsnr = new ObexListener(ObexTransport.Bluetooth);

            lsnr.Start();
            // For each connection
            ObexListenerContext ctx = lsnr.GetContext();
            ObexListenerRequest req = ctx.Request;

            String[] pathSplits = req.RawUrl.Split('/');
            String   filename   = pathSplits[pathSplits.Length - 1];

            req.WriteFile(filename);
            //
            lsnr.Stop();
        }
Exemplo n.º 11
0
        public void SimplePut1()
        {
            byte[] requests          = NewWholeProcessTests_Data.SimplePut1_ExpectedRequests;
            byte[] expectedResponses = SimplePut1_Responses;
            //
            ObexListenerContext ctx = DoTest(requests, expectedResponses);

            //
            AssertHeader(ctx, "NAME", "aaaa.txt");
            AssertHeader(ctx, "LENGTH", "4");
            Assert.AreEqual(2, ctx.Request.Headers.Count, "Headers.Count");
            //Console.WriteLine(String.Join(",", ctx.Request.Headers.AllKeys));
            //
            Stream content = new MemoryStream();

            Stream_CopyTo(ctx.Request.InputStream, content);
            Assert.AreEqual(4, content.Length, "content.Length");
        }
Exemplo n.º 12
0
        private void ReceiveFile()
        {
            textBox1.Text += ("Rozpoczynam nasluchiwanie na nowe wiadomosci...") + Environment.NewLine;

            // wykonuje do momenu gdy nie zostaniemy rozlaczeni z urzadzeniem
            while (czySparowano)
            {
                var listener = new ObexListener(ObexTransport.Bluetooth);
                listener.Start();
                ObexListenerContext ctx        = listener.GetContext();
                ObexListenerRequest req        = ctx.Request;
                String[]            pathSplits = req.RawUrl.Split('/');
                String filename = pathSplits[pathSplits.Length - 1];
                req.WriteFile(filename);
                textBox1.Text += (filename);
                listener.Stop();
            }
        }
Exemplo n.º 13
0
        public void DealWithRequest()
        {
            while (ol.IsListening)
            {
                try
                {
                    ObexListenerContext olc = ol.GetContext();
                    ObexListenerRequest olr = olc.Request;
                    string filename         = Uri.UnescapeDataString(olr.RawUrl.TrimStart(new char[] { '/' }));
                    olr.WriteFile(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\" + DateTime.Now.ToString("yyMMddHHmmss") + " " + filename);

                    this.Invoke(new AddToListDelegate(AddToList), new object[] { filename });
                }
                catch (Exception)
                {
                    break;
                }
            }
        }
Exemplo n.º 14
0
        private void receiveFile()//收文件方法
        {
            ObexListenerContext context = null;
            ObexListenerRequest request = null;

            while (listener.IsListening)
            {
                context = listener.GetContext();//获取监听上下文
                if (context == null)
                {
                    break;
                }
                request = context.Request;                                   //获取请求
                string uriString   = Uri.UnescapeDataString(request.RawUrl); //将uri转换成字符串
                string recFileName = recDir + uriString;
                request.WriteFile(recFileName);                              //接收文件
                Console.WriteLine("收到文件" + uriString.TrimStart(new char[] { '/' }));
            }
        }
Exemplo n.º 15
0
        private void DoTest_Put_ContentLength(byte[] requests, byte[] expectedResponses,
                                              int?expectedContentLengthHeaderValue)
        {
            ObexListenerContext ctx = DoTest(requests, expectedResponses);
            ObexListenerRequest req = ctx.Request;

            //
            if (expectedContentLengthHeaderValue.HasValue)
            {
                Assert.AreEqual(expectedContentLengthHeaderValue.Value, req.ContentLength64, "ContentLength64");
            }
            //
            AreEqualBuffers(NewWholeProcessTests_Data.SimplePut1_Data, (MemoryStream)req.InputStream);
            //
            MemoryStream data2 = new MemoryStream();

            System.Threading.ThreadStart dlgt = delegate {
                req.WriteFile(data2);
            };
            IAsyncResult ar        = dlgt.BeginInvoke(null, null);
            bool         signalled = ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2));

            if (!signalled)
            {
                // Need to kill the WriteFile thread or there'll be big CPU usage!
                data2.Close(); // Cause WriteFile to fail!
                bool signalledAfter = ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2));
                Assert.IsTrue(signalledAfter, "WriteFile aborted but still hung");
                try {
                    dlgt.EndInvoke(ar);
                } catch (ObjectDisposedException) {
                }
            }
            else
            {
                Assert.IsTrue(signalled, "WriteFile hung");
                dlgt.EndInvoke(ar);
            }
            AreEqualBuffers(NewWholeProcessTests_Data.SimplePut1_Data, data2);
            Assert.IsTrue(signalled, "WriteFile hung [end]");
        }
Exemplo n.º 16
0
        public void DealWithRequest()
        {
            while (listener.IsListening)
            {
                try
                {
                    ObexListenerContext olc = listener.GetContext();
                    ObexListenerRequest olr = olc.Request;
                    string filename         = Uri.UnescapeDataString(olr.RawUrl.TrimStart(new char[] { '/' }));
                    olr.WriteFile("\\My Documents\\" + DateTime.Now.ToString("yyMMddHHmmss") + " " + filename);

                    items.Add(filename);
                }
                catch (Exception)
                {
                    break;
                }

                this.Invoke(new EventHandler(RedrawList));
            }
        }
Exemplo n.º 17
0
        public MemoryStream IniciarRecepcionImagenBT()
        {
            MemoryStream archivo = new MemoryStream();

            BluetoothRadio radio = BluetoothRadio.PrimaryRadio;

            if (radio == null)
            {
                throw new Exception("No bluetooth device connected");
            }
            else
            {
                radio.Mode = RadioMode.Discoverable;
            }


            ObexListener receptorImagenes = new ObexListener(ObexTransport.Bluetooth);

            receptorImagenes.Start();
            //MessageBox.Show("Esperando imagen", "Receptor Imagenes", MessageBoxButtons.OK);
            ObexListenerContext contexto = receptorImagenes.GetContext();
            //MessageBox.Show("Imagen Recibida", "Receptor Imagenes", MessageBoxButtons.OK);

            ObexListenerRequest req = contexto.Request;

            string archivoDireccion = req.RawUrl;
            string extension        = req.RawUrl.Split('.').ToList().LastOrDefault();

            archivo = new MemoryStream();
            req.InputStream.CopyTo(archivo);
            string b64 = Convert.ToBase64String(archivo.ToArray());

            //req.WriteFile("."+ archivoDireccion);
            //File.WriteAllBytes("./b64." + extension, archivo.ToArray());
            receptorImagenes.Stop();

            return(archivo);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Receive (fetch) a file from an attached external bluetooth device.
        /// You must first Initialise, then set the device.
        /// </summary>
        /// <param name="fileName">The location to save the received file.</param>
        /// <returns>A result status message "True" or "False".</returns>
        public static Primitive ReceiveFile(Primitive fileName)
        {
            BluetoothDeviceInfo info = GetBluetoothDeviceInfo(device);

            if (null == info || null == bluetoothClient)
            {
                lastError = "Device or client not set";
                return("False");
            }
            try
            {
                ObexListener ol = new ObexListener(ObexTransport.Bluetooth);
                ol.Start();
                while (ol.IsListening)
                {
                    try
                    {
                        ObexListenerContext olc = ol.GetContext();
                        ObexListenerRequest olr = olc.Request;
                        olr.WriteFile(fileName);
                        ol.Stop();
                    }
                    catch (Exception ex)
                    {
                        Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                        lastError = ex.Message;
                        return("False");
                    }
                }
                return("True");
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                lastError = ex.Message;
                return("False");
            }
        }
Exemplo n.º 19
0
        private ObexListenerContext DoTest(byte[] requests, byte[] expectedResponses,
                                           bool expectError, out Exception resultException)
        {
            MemoryStream peerRequests_ = new MemoryStream(requests, false);
            Stream       peerRequests  = ModifyReadStream(peerRequests_);
            MemoryStream ourResponses  = new MemoryStream();
            TwoWayStream peer          = new TwoWayStream(peerRequests, ourResponses);
            //
            SocketAdapter       s = CreateSocketAdapter(peer);
            ObexListenerContext ctx;

            try {
                ctx             = new ObexListenerContext(s);
                resultException = null;
            } catch (Exception ex) {
                // If test error expected we DO want to check that the
                // response packets are correct.  Otherwise just fail.
                if (expectError)
                {
                    resultException = ex;
                    ctx             = null;
                }
                else
                {
                    // Unexpected!
                    throw;
                }
            }
            //
            Assert.AreEqual(expectedResponses, ourResponses.ToArray(), "ourResponses");
            if (resultException != null)
            {
                Debug.Assert(ctx == null);
            }
            return(ctx);
        }
Exemplo n.º 20
0
 private void AssertHeader(ObexListenerContext ctx, string headerName, string expectedValue)
 {
     Assert.AreEqual(expectedValue, ctx.Request.Headers[headerName], "Headers['" + headerName + "']");
 }
Exemplo n.º 21
0
        public void DealWithRequest()
        {
            while (ol.IsListening)
            {
                //receive files via bluetooth
                try
                {
                    ObexListenerContext olc = ol.GetContext();
                    ObexListenerRequest olr = olc.Request;

                    string filename = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) +
                                      "\\" +
                                      DateTime.Now.ToString("dd-MM-yy HHmm") +
                                      " " +
                                      Uri.UnescapeDataString(olr.RawUrl.TrimStart(new char[] { '/' }));
                    //remove newline
                    filename = filename.Substring(0, filename.Length - 1);
                    Console.Write("filetype: " + filename.Substring(filename.Length - 3, 3));
                    olr.WriteFile(filename);

                    //add filename to fileList
                    DoFileListUpdate(filename);

                    if (filename.Substring(filename.Length - 3, 3).Equals("jpg") ||
                        filename.Substring(filename.Length - 3, 3).Equals("JPG") ||
                        filename.Substring(filename.Length - 3, 3).Equals("png") ||
                        filename.Substring(filename.Length - 3, 3).Equals("PNG") ||
                        filename.Substring(filename.Length - 3, 3).Equals("GIF") ||
                        filename.Substring(filename.Length - 3, 3).Equals("gif"))
                    {
                        //image upload to picasa

                        Uri postUri = new Uri(PicasaQuery.CreatePicasaUri(username, albumid));

                        System.IO.FileInfo   fileInfo   = new System.IO.FileInfo(filename);
                        System.IO.FileStream fileStream = fileInfo.OpenRead();
                        PicasaEntry          entry      = (PicasaEntry)picasaService.Insert(postUri, fileStream, "image/jpeg", filename);
                        fileStream.Close();
                        //image properties
                        entry.Title.Text   = "Gogbot09: " + olr.RawUrl.TrimStart(new char[] { '/' });
                        entry.Summary.Text = "User content for GOGBOT 2009 festival, provided by bluetooth device: " +
                                             olr.UserHostAddress +
                                             " on: " +
                                             DateTime.Now.ToString("dd-MM-yy HHmm");
                        entry.Media.Keywords.Value = "gogbot, GOGBOT09, gogbot2009, bluetube";
                        //entry.Location = new GeoRssWhere();
                        //entry.Location.Latitude = 37;
                        //entry.Location.Longitude = -122;

                        PicasaEntry updatedEntry = (PicasaEntry)entry.Update();
                        Console.WriteLine("Photo: " + olr.RawUrl.TrimStart(new char[] { '/' }) + " uploaded.");
                    }
                    else
                    {
                        //upload video to youtube
                        Video newVideo = new Video();

                        newVideo.Title = "Gogbot09: " + olr.RawUrl.TrimStart(new char[] { '/' });
                        newVideo.Tags.Add(new MediaCategory("People", YouTubeNameTable.CategorySchema));
                        newVideo.Keywords    = "gogbot, GOGBOT09, gogbot2009, bluetube";
                        newVideo.Description = "User content for GOGBOT 2009 festival, provided by bluetooth device: " +
                                               olr.UserHostAddress +
                                               " on: " +
                                               DateTime.Now.ToString("dd-MM-yy HHmm");
                        newVideo.YouTubeEntry.Private = false;
                        newVideo.Tags.Add(new MediaCategory("uploaded_through_bluetube",
                                                            YouTubeNameTable.DeveloperTagSchema));

                        //newVideo.YouTubeEntry.Location = new GeoRssWhere(37, -122);
                        // alternatively, you could just specify a descriptive string
                        newVideo.YouTubeEntry.setYouTubeExtension("location", "Vrije Universiteit, Amsterdam");

                        newVideo.YouTubeEntry.MediaSource = new MediaFileSource(filename, "video/3gpp");
                        Video video = request.Upload(newVideo);

                        //Check status
                        if (video.IsDraft)
                        {
                            Console.WriteLine("Video is not live.");
                            string stateName = video.Status.Name;
                            if (stateName == "processing")
                            {
                                Console.WriteLine("Video is still being processed.");
                            }
                            else if (stateName == "rejected")
                            {
                                Console.Write("Video has been rejected because: ");
                                Console.WriteLine(video.Status.Value);
                                Console.Write("For help visit: ");
                                Console.WriteLine(video.Status.Help);
                            }
                            else if (stateName == "failed")
                            {
                                Console.Write("Video failed uploading because:");
                                Console.WriteLine(video.Status.Value);
                                Console.Write("For help visit: ");
                                Console.WriteLine(video.Status.Help);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }