Ejemplo n.º 1
0
 /// <summary>
 /// Gets called when a NFC device is detected.
 /// </summary>
 /// <param name="sender">ProximityDevice instance</param>
 private void DeviceArrived(ProximityDevice sender)
 {
     Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         _logText = "\nDetected at " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second;
     });
 }
Ejemplo n.º 2
0
        public MainPage()
        {
            this.InitializeComponent();

            Synopsis.Text += "\n\n";
            try
            {
                proximityDevice = ProximityDevice.GetDefault();
                Synopsis.Text  += proximityDevice.DeviceId + "\n\n";
            }
            catch (Exception e)
            {
                Synopsis.Text += e.ToString() + "\n\n";
            }

            if (proximityDevice != null)
            {
                proximityDevice.DeviceArrived  += DeviceArrived;
                proximityDevice.DeviceDeparted += DeviceDeparted;
            }
            else
            {
                Synopsis.Text += "No proximity device found\n";
            }
        }
Ejemplo n.º 3
0
        private async Task <ProximityDevice> GetNfcDevice()
        {
            ProximityDevice device = null;

            string selectorString = ProximityDevice.GetDeviceSelector();

            DeviceInformationCollection deviceInfoCollection =
                await DeviceInformation.FindAllAsync(selectorString, new List <string>() { "{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2" });

            if (deviceInfoCollection.Count > 0)
            {
                foreach (DeviceInformation info in deviceInfoCollection)
                {
                    Log("Found: " + info.Name);
                    foreach (string prop in info.Properties.Keys)
                    {
                        object value = info.Properties[prop];
                        if (null != value)
                        {
                            Log(prop + ": " + value.ToString());
                        }
                    }
                    device = ProximityDevice.FromId(info.Id);
                }
            }

            return(device);
        }
Ejemplo n.º 4
0
 private void messageTransmittedHandler(ProximityDevice sender, long messageId)
 {
     Deployment.Current.Dispatcher.BeginInvoke(() =>
     {
         StatusTextBlock.Text = "NFC Tag Written!";
     });
 }
Ejemplo n.º 5
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //
            // TODO: Insert code to perform background work
            //
            // If you start any asynchronous methods here, prevent the task
            // from closing prematurely by using BackgroundTaskDeferral as
            // described in http://aka.ms/backgroundtaskdeferral

            _deferral = taskInstance.GetDeferral();

            await Task.Delay(30000);

            bs = new RateSensor();
            bs.RateSensorInit();

            await Task.Delay(1000);

            bs.RateMonitorON();

            deviceWatcher = DeviceInformation.CreateWatcher(
                "System.ItemNameDisplay:~~\"Adafruit\"",
                new string[] {
                "System.Devices.Aep.DeviceAddress",
                "System.Devices.Aep.IsConnected"
            },
                DeviceInformationKind.AssociationEndpoint);

            deviceWatcher.Added   += DeviceWatcher_Added;
            deviceWatcher.Removed += DeviceWatcher_Removed;
            deviceWatcher.Start();

            // NFC
            proxDevice = ProximityDevice.GetDefault();
            if (proxDevice != null)
            {
                proxDevice.SubscribeForMessage("NDEF", messagedReceived);
            }
            else
            {
                Debug.WriteLine("No proximity device found\n");
            }

            this.timer = ThreadPoolTimer.CreateTimer(Timer_Tick, TimeSpan.FromSeconds(2));

            try
            {
                await Task.Run(async() =>
                {
                    while (true)
                    {
                        await Task.Delay(100000);
                    }
                });
            }
            catch (Exception ex)
            {
            }
            deviceWatcher.Stop();
        }
Ejemplo n.º 6
0
 private void MessageWrittenHandler(ProximityDevice sender, long messageid)
 {
     // Stop publishing the message
     StopPublishingMessage(false);
     // Update status text for UI
     SetStatusOutput(_loader.GetString("StatusMessageWritten"));
 }
Ejemplo n.º 7
0
        public MainPage()
        {
            // Initialize this page's components that were set up via the UI designer.
            InitializeComponent();

            // Set up Corona to automatically start up when the control's Loaded event has been raised.
            // Note: By default, Corona will run the "main.lua" file in the "Assets\Corona" directory.
            //       You can change the defaults via the CoronaPanel's AutoLaunchSettings property.
            fCoronaPanel.AutoLaunchEnabled = true;

            // Set up the CoronaPanel control to render fullscreen via the DrawingSurfaceBackgroundGrid control.
            // This significantly improves the framerate and is the only means of achieving 60 FPS.
            fCoronaPanel.BackgroundRenderingEnabled = true;
            fDrawingSurfaceBackgroundGrid.SetBackgroundContentProvider(fCoronaPanel.BackgroundContentProvider);
            fDrawingSurfaceBackgroundGrid.SetBackgroundManipulationHandler(fCoronaPanel.BackgroundManipulationHandler);

            // Add a Corona event handler which detects when the Corona project has been loaded, but not started yet.
            fCoronaPanel.Runtime.Loaded += OnCoronaRuntimeLoaded;


            // Add a Corona event handler which detects when the Corona project has been started.
            fCoronaPanel.Runtime.Started += OnCoronaRuntimeStarted;

            //For sending and receiving messages
            _proximityDevice = ProximityDevice.GetDefault();
            if (_proximityDevice == null)
            {
                // Device failed to load.
                // TO DO: Add error message
            }
        }
Ejemplo n.º 8
0
 void messageWrittenHandler(ProximityDevice sender, long publishedMessageId)
 {
     Deployment.Current.Dispatcher.BeginInvoke(() =>
     {
         MessageBox.Show("The message is written");
     });
 }
Ejemplo n.º 9
0
 private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
 {
     try
     {
         using (var reader = DataReader.FromBuffer(message.Data))
         {
             reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
             string receivedString = reader.ReadString(reader.UnconsumedBufferLength / 2 - 1);
             Debug.WriteLine("Received message from NFC: " + receivedString);
             Url = receivedString;
             if (receivedString == "semc://liveware/A1/1/NT1/2/smarttags")
             {
                 tray.NFCRedDetected();
             }
             else if (receivedString == "semc://liveware/A1/1/NT1/3/smarttags")
             {
                 tray.NFCBlackDetected();
             }
         }
     }
     catch (Exception e)
     {
         Debug.WriteLine(e.StackTrace);
     }
 }
 public WriteLaunchAppTag()
 {
     InitializeComponent();
     device         = ProximityDevice.GetDefault();
     writableTagId  = device.SubscribeForMessage("WriteableTag", checkWritableTagSize);
     inputText.Text = appIdNokiaMusic;
 }
 // 対応端末を発見した
 async void proximityDevice_DeviceArrived(ProximityDevice sender)
 {
     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
     {
         TextMessage.Text = @"デバイスを見つけました";
     });
 }
        //URI message received
        //Not used for now....
        private void WindowsUriHandler(ProximityDevice sender, ProximityMessage message)
        {
            try
            {
                var buffer = message.Data.ToArray();
                var sUri   = Encoding.Unicode.GetString(buffer, 0, buffer.Length);

                //remove null charater if present
                if (sUri[sUri.Length - 1] == '\0')
                {
                    sUri = sUri.Remove(sUri.Length - 1);
                }

                var    uri = new Uri(sUri);
                string s   = "WindowsUri : \n" + uri + "\n\n";
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Go to: " + s);
                    //update the UI
                });
            }
            catch (Exception e)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(e.Message);
                });
            }
        }
Ejemplo n.º 13
0
        private void OnMessageReceived(ProximityDevice sender, ProximityMessage message)
        {
            if (state == NfcManager.ProtoState.Ready)
            {
                return;
            }

            state = NfcManager.ProtoState.NotReady;

            try
            {
                String                 msg        = message.DataAsString.Substring(0, message.DataAsString.IndexOf('\0'));
                MemoryStream           stream     = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(msg));
                DataContractSerializer serializer = new DataContractSerializer(typeof(InitialMessage));
                stream.Position = 0;
                InitialMessage adversaryTime = (InitialMessage)serializer.ReadObject(stream);
                isMaster = (initialMessage.devicetime > adversaryTime.devicetime);
                state    = NfcManager.ProtoState.Ready;
                proximityDevice.StopSubscribingForMessage(subscribeId);
                proximityDevice.StopPublishingMessage(publishId);
                subscribeId = -1;
                publishId   = -1;
                notifyReady();
            }
            catch (SerializationException)
            {
            }
        }
Ejemplo n.º 14
0
        public void PingAdversary(ProximityDevice device, NotifyNfcReady notify)
        {
            if (subscribeId != -1)
            {
                proximityDevice.StopSubscribingForMessage(subscribeId);
                subscribeId = -1;
            }

            if (publishId != -1)
            {
                proximityDevice.StopPublishingMessage(publishId);
                publishId = -1;
            }

            if (state == NfcManager.ProtoState.Busy)
            {
                return;
            }

            state       = NfcManager.ProtoState.NotReady;
            notifyReady = notify;
            initialMessage.devicetime = random.NextDouble();
            MemoryStream           stream     = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(initialMessage.GetType());

            serializer.WriteObject(stream, initialMessage);
            stream.Position = 0;
            var dataWriter = new DataWriter();

            dataWriter.WriteBytes(stream.GetBuffer());
            proximityDevice = device;
            publishId       = proximityDevice.PublishBinaryMessage("Windows.CarTrumps", dataWriter.DetachBuffer());
            subscribeId     = proximityDevice.SubscribeForMessage("Windows.CarTrumps", OnMessageReceived);
        }
Ejemplo n.º 15
0
        private void OnDeviceArrived(ProximityDevice sender)
        {
            var stopwatch = (Stopwatch)null;

            if (Debug)
            {
                stopwatch = new Stopwatch();
                stopwatch.Start();
            }

            if (subscriptionIdNdef == 0)
            {
                subscriptionIdNdef = sender.SubscribeForMessage("NDEF", OnMessageReceived);
            }

            var args = new DeviceStatusChangedEventArgs()
            {
                DeviceStatus = StatusEnum.DeviceArrived
            };

            if (Debug)
            {
                stopwatch.Stop();
                args.ExecutionTime = stopwatch.Elapsed;
                args.MethodName    = "TagReader.OnDeviceArrived";
            }

            OnDeviceStatusChanged(this, args);
        }
Ejemplo n.º 16
0
 // no args
 public void registerNdef(string args)
 {
     Debug.WriteLine("Registering for NDEF");
     proximityDevice     = ProximityDevice.GetDefault();
     subscribedMessageId = proximityDevice.SubscribeForMessage("NDEF", MessageReceivedHandler);
     DispatchCommandResult();
 }
Ejemplo n.º 17
0
        private async void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
        {
            // Get the raw NDEF message data as byte array
            var rawMsg = message.Data.ToArray();
            // Let the NDEF library parse the NDEF message out of the raw byte array
            var ndefMessage = NdefMessage.FromByteArray(rawMsg);

            // Analysis result
            var tagContents = new StringBuilder();

            // Parse tag contents
            try
            {
                // Clear bitmap if the last tag contained an image
                SetStatusImage(null);

                // Parse the contents of the tag
                await ParseTagContents(ndefMessage, tagContents);

                // Update status text for UI
                SetStatusOutput(string.Format(_loader.GetString("StatusTagParsed"), tagContents));
            }
            catch (Exception ex)
            {
                SetStatusOutput(string.Format(_loader.GetString("StatusNfcParsingError"), ex.Message));
            }
        }
Ejemplo n.º 18
0
        private void messageReceived(ProximityDevice proximityDevice, ProximityMessage message)
        {
            var rawMsg = WindowsRuntimeBufferExtensions.ToArray(message.Data);
            //このrawMsgをNDEF解析すればよいようだ
            //NDEF解析はOSでやってくれないらしい。OSがやるのはNFPだけか。

            string str = "メッセージ";

            switch (rawMsg[3])
            {
            case (byte)'T':
                str += "TEXT";
                break;

            case (byte)'U':
                str += "URI";
                break;

            case (byte)'S':
                if (rawMsg[4] == (byte)'p')
                {
                    str += "SmartPoster";
                }
                break;
            }
            showToast(str);
        }
Ejemplo n.º 19
0
    /**
     * Start/stop listening on the proximity device for a tag.
     *
     * @param input {object}
     * @param input.stop {bool} True to stop listening.
     * @param input.gotTag {Function(Buffer)} The callback for when a tag is received.
     * @return true on success. false if there is no such device.
     */
    public async Task <object> Invoke(dynamic input)
    {
        ProximityDevice dev     = ProximityDevice.GetDefault();
        bool            success = false;

        if (dev != null)
        {
            if (input.stop)
            {
                // Stop listening.
                if (subscriptionId >= 0)
                {
                    dev.StopSubscribingForMessage(subscriptionId);
                    subscriptionId = -1;
                }

                gotTagCallback = null;
            }
            else if (subscriptionId < 0)
            {
                // Start listening.
                gotTagCallback = input.gotTag;
                subscriptionId = dev.SubscribeForMessage("NDEF", new MessageReceivedHandler(GotTag));
            }
            success = true;
        }

        return(success);
    }
 void DeviceDeparted(ProximityDevice proximityDevice)
 {
     var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
     {
         ProximityDeviceEventsOutputText.Text += "Proximate device departed\n";
     });
 }
Ejemplo n.º 21
0
 void _proximityDevice_DeviceArrived(ProximityDevice sender)
 {
     Deployment.Current.Dispatcher.BeginInvoke(() =>
     {
         StatusTextBlock.Text = "Device detected.";
     });
 }
Ejemplo n.º 22
0
        public async Task Init()
        {
            proximityDevice = await GetNfcDevice();

            if (proximityDevice != null)
            {
                Log("Successfully retrieved Device!");
                Log($"Device ID: {proximityDevice.DeviceId} ");
                Log($"Bits Per Second: {proximityDevice.BitsPerSecond} ");
                Log($"Max Message Bytes: {proximityDevice.MaxMessageBytes}");

                // Reference: https://msdn.microsoft.com/en-us/library/windows/apps/hh701129.aspx
                TryToSubscribe("Windows.Contoso", messageReceivedHandler);

                proximityDevice.DeviceArrived  += ProximityDeviceArrived;
                proximityDevice.DeviceDeparted += ProximityDeviceDeparted;

                Log("Proximity device initialized.");

                //publish the message to devices that listen
                PublishInfo();
            }
            else
            {
                Log("Failed to initialized proximity device.");
            }
        }
Ejemplo n.º 23
0
 private void MessageWrittenHandler(ProximityDevice sender, long messageid)
 {
     // Stop publishing the message
     StopPublishingMessage(false);
     // Update status text for UI
     SetStatusOutput(AppResources.StatusMessageWritten);
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Gets called when a NFC device is detected.
 /// </summary>
 /// <param name="sender">ProximityDevice instance</param>
 private void DeviceArrived(ProximityDevice sender)
 {
     Dispatcher.BeginInvoke(() =>
     {
         logText = "\nDetected at " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second;
     });
 }
        public bool doInitialise(Int32 cbUIDPtr, Int32 cbStatePtr, out String AMessage)
        {
            recordList      = new List <NdefRecord>();
            proximityDevice = ProximityDevice.GetDefault();

            ptr         = new IntPtr(cbUIDPtr);
            callbackUID = (cbUID)Marshal.GetDelegateForFunctionPointer(ptr, typeof(cbUID));

            ptr           = new IntPtr(cbStatePtr);
            callbackState = (cbState)Marshal.GetDelegateForFunctionPointer(ptr, typeof(cbState));

            if (proximityDevice != null)
            {
                proximityDevice.DeviceArrived  += ProximityDeviceArrived;
                proximityDevice.DeviceDeparted += ProximityDeviceDeparted;
                proximityDevice.SubscribeForMessage("NDEF", MessageReceivedHandler);
                AMessage = "Proximity device initialized. ID: " + proximityDevice.DeviceId;
                return(true);
            }
            else
            {
                AMessage = "Failed to initialize proximity device.";
                return(false);
            }
        }
        /// <summary>
        /// Function to convert the selected provisioning package into chunk and send it over NFC.
        /// </summary>
        /// <returns></returns>
        private async Task InternalTransferHandlerAsync(CancellationToken ct)
        {
            rootPage.NotifyUser("Tap device to transfer package.", NotifyType.StatusMessage);

            if (null == provisioningPackageFile)
            {
                rootPage.NotifyUser("Select a package before transferring.", NotifyType.ErrorMessage);
                return;
            }

            IBuffer buffer = await FileIO.ReadBufferAsync(provisioningPackageFile);

            if (null == buffer)
            {
                rootPage.NotifyUser("Something was wrong. Choose another package and retry again.", NotifyType.ErrorMessage);
                return;
            }

            ProximityDevice proximityDevice = ProximityDevice.GetDefault();

            if (null == proximityDevice)
            {
                rootPage.NotifyUser("You'll need to turn on NFC to transfer the package. Go to NFC settings.", NotifyType.ErrorMessage);
                return;
            }

            // Start to format the provisioning package into chunks, and transfer it to another device to be provisioned.
            await ConvertToNfcMessageAsync(buffer, proximityDevice, NfcMessageHandlerAsync, ct);

            rootPage.NotifyUser("Success!", NotifyType.StatusMessage);
        }
Ejemplo n.º 27
0
        void DeviceArrived(ProximityDevice proximityDevice)
        {
            var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                Synopsis.Text += "Proximate device arrived\n\n";
                Synopsis.Text += "Wi-Fi Direct requested\n\n";
                Synopsis.Text += "ServerConnected\n\n";
            });

            //subscribedMessageId = proximityDevice.SubscribeForMessage("NDEF:wkt.HelloWorld", messageReceived);
            //subscribedMessageId = -1;

            //if(publishedUriId == -1)
            //    PublishLaunchApp();

            publishedUriId =
                proximityDevice.PublishUriMessage(new Uri("http://www.microsoft.com"));

            if (publishedUriId != -1)
            {
                proximityDevice.StopPublishingMessage(publishedUriId);
            }

            //SplitAndCombine.combineFile();

            //Connecting();
        }
        /// <summary>
        /// Function to handle the chunk message and push the NFC message to proximity device.
        /// </summary>
        /// <param name="proximityDevice">ProximityDevice instance to be used.</param>
        /// <param name="chuckData">IBuffer to chunk message.</param>
        private static async Task NfcMessageHandlerAsync(ProximityDevice proximityDevice, IBuffer chuckData, CancellationToken ct)
        {
            using (var publishedEvent = new AutoResetEvent(false))
            {
                long publishedMessageId = INVALID_PUBLISHED_MESSAGE_ID;

                publishedMessageId = proximityDevice.PublishBinaryMessage(
                    NFC_PROV_MESSAGE_PROTOCOL_NAME,
                    chuckData, (
                        Windows.Networking.Proximity.ProximityDevice device,
                        long messageId
                        ) =>
                {
                    publishedEvent.Set();
                });

                if (INVALID_PUBLISHED_MESSAGE_ID == publishedMessageId)
                {
                    throw new System.ArgumentException("Published message ID returned was invalid.");
                }

                // Wait for the event to be signaled on a threadpool thread so we don't block the UI thread.
                await Task.Run(() =>
                {
                    // Wait for the message transmitted handler to ensure the NFC message has been processed internally.
                    WaitHandle.WaitAny(new WaitHandle[] { publishedEvent, ct.WaitHandle });
                    ct.ThrowIfCancellationRequested();
                });
            }
        }
Ejemplo n.º 29
0
        private void PublishLaunchApp(ProximityDevice proximityDevice)
        {
            //var proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

            if (proximityDevice != null)
            {
                                // The format of the app launch string is:
                                // <args>\tWindows\t<AppFamilyBasedName>\tWindowsPhone\t<AppGUID>
                                // The string is tab delimited.

                                // The <args> string must have at least one character.
                                string launchArgs = "user=default";


                                                      // The format of the AppFamilyBasedName is: PackageFamilyName!PRAID.
                                string praid = "App"; // The Application Id value from your package.appxmanifest.
                                string appFamilyBasedName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;


                // GUID is PhoneProductId value from you package.appxmanifest
                // NOTE: The GUID will change after you associate app to the app store
                // Consider using windows.applicationmodel.store.currentapp.appid after the app is associated to the store.
                string appGuid = "{55d006ef-be06-4019-bc6d-ec38f28a5304}";

                string launchAppMessage = launchArgs +
                                          "\tWindows\t" + appFamilyBasedName +
                                          "\tWindowsPhone\t" + appGuid;

                var dataWriter = new Windows.Storage.Streams.DataWriter();
                dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
                dataWriter.WriteString(launchAppMessage);
                var launchAppPubId = proximityDevice.PublishBinaryMessage("LaunchApp:WriteTag", dataWriter.DetachBuffer());
            }
        }
Ejemplo n.º 30
0
 // デバイスを認識した
 void proximityDevice_DeviceArrived(ProximityDevice sender)
 {
     Dispatcher.BeginInvoke(new Action(() =>
     {
         TextMessage.Text = @"デバイスを見つけました";
     }));
 }