粒子滤波 应用_如何使用NativeScript开发粒子物联网应用

粒子滤波 应用

If you're developing any type of IoT product, inevitably you'll need some type of mobile app. While there are easy ways, they're not for production use.

如果您要开发任何类型的物联网产品,则不可避免地需要某种类型的移动应用程序。 尽管有简单的方法 ,但它们并不用于生产。

In this tutorial, we'll talk about the basics of Particle app development. You'll learn about some of the many app frameworks you can take advantage of. Plus there's libraries, tricks, and tools along the way to make your life a lot easier.

在本教程中,我们将讨论粒子应用程序开发的基础知识。 您将了解许多可以利用的应用程序框架。 此外,还有各种库,技巧和工具,使您的生活更加轻松。

应用框架 (App Frameworks)

Sometimes it's dang near irritating to program multiple applications natively. You see, Swift (or Objective C 🤮) and Java aren't terrible at first glance (well, maybe except for Obj-C 🤮). But when you're resource constrained, you have to figure out a new game plan. That's where App Frameworks come in.

有时,本地编写多个应用程序很烦人。 您会发现,Swift(或Objective C🤮)和Java乍一看并不糟糕(嗯,也许是Obj-C except除外)。 但是,如果您资源有限,就必须制定新的游戏计划。 那就是App Framework的用武之地。

These frameworks allow an app developer to write, build and test cross platform apps. In some cases, the frameworks convert your app into native code. That means that they run as fast and as well as one written in Swift or Java.

这些框架允许应用程序开发人员编写,构建和测试跨平台应用程序。 在某些情况下,框架会将您的应用程序转换为本机代码。 这意味着它们的运行速度和使用Swift或Java编写的速度一样快。

I did the research and as of January 2020, here are some of the most supported frameworks:

我进行了研究,截至2020年1月,以下是一些最受支持的框架:

The list goes on for days.

该列表持续了几天。

I've used a few of these frameworks in the past. I've built a Meteor app which (surprisingly) worked. In the end I had to pick one though. What did I go with?

我过去曾经使用过其中一些框架。 我构建了一个(令人惊讶的)有效的Meteor应用程序。 最后,我不得不选一个。 我去了什么?

NativeScript.

NativeScript。

For the most part, NativeScript's documentation and on-boarding experience is fantastic. Not only can you preview your app inside an emulator but you can load it directly to your phone too!

在大多数情况下,NativeScript的文档和入门经验都很棒。 您不仅可以在模拟器中预览应用程序,还可以将其直接加载到手机中!

One of the cool things about NativeScript is that it supports TypeScript. TypeScript is a superset of JavaScript with some extra wiz-bang features.

NativeScript的优点之一是它支持TypeScript。 TypeScript是JavaScript的超集,具有一些额外的wiz-bang功能。

Unlike other languages, JavaScript technically has no types. If you've done any Particle development you likely know what a type is. We're talking about int, String, float and more. i.e. they're directives to to make sure your JavaScript code stays consistent.

与其他语言不同,JavaScript技术上没有类型。 如果完成了任何Particle开发,您可能会知道类型是什么。 我们正在谈论intStringfloat等。 也就是说,它们是确保您JavaScript代码保持一致的指令。

NativeScript is also compatible with most major JavaScript web frameworks. This includes Vue.Js and Angular.

NativeScript还与大多数主要JavaScript Web框架兼容。 这包括Vue.JsAngular

I've only noticed one major drawback thus far: the mobile preview mode (tns preview command) does not pay well with native libraries. If you have some native platform specific libraries, you'll have to use the emulator or a device (if you have one).

到目前为止,我仅注意到一个主要缺点:移动预览模式( tns preview命令)不能与本机库一起使用。 如果您有一些本机平台特定的库,则必须使用仿真器或设备(如果有的话)。

If you're gung-ho and you want to build multiple apps in their respective languages, the more power to you. There is an advantage over the above frameworks: tried and true Particle SDKs.

如果您是gung-ho,并且想要以各自的语言来构建多个应用程序,那么您将获得更多的功能。 与上述框架相比,它有一个优势:久经考验的真实的SDK。

可用的库和SDK (Available Libraries & SDKs)

Particle has gone out of their way to make app development a little easier. This is thanks to the massive development work that has gone into their own SDKs. Yup, gone are the days you have to write manual HTTP request handlers.

Particle已竭尽全力使应用程序开发更加轻松。 这要归功于他们自己的SDK中的大量开发工作。 是的,您不得不编写手动HTTP请求处理程序的日子已经一去不复返了。

Here's a link to both the iOS and Android SDKs:

这是iOS和Android SDK的链接:

Though we won't be covering them here, they reflect all the potential calls that you can make using the Cloud API.

尽管我们不会在这里介绍它们,但是它们反映了您可以使用Cloud API进行的所有潜在调用

Speaking of Cloud API, Particle has also developed a Node.js library as well. As you can imagine, you can use this for your server side code or JavaScript based app frameworks. Sadly, it doesn't work with NativeScript. Frameworks that use a WebView should be more compatible.

说到Cloud API,Particle还开发了一个Node.js库。 可以想象,您可以将其用于服务器端代码或基于JavaScript的应用程序框架。 可悲的是,它不适用于NativeScript。 使用WebView的框架应该更兼容。

In the case of this tutorial, we'll be mostly focusing on the Cloud API. This way you have a good understanding of the overall system. It may seem intimidating but if you do it right, you'll get the hang of it real fast.

在本教程中,我们将主要关注Cloud API。 这样,您对整个系统有了很好的了解。 这似乎令人生畏,但是如果您做对了,您将很快掌握其实质。

进行API调用 (Making API Calls)

In NativeScript you can't use libraries like [request](https://github.com/request/request). (Which happens to be the library Particle's very own DMC used in the CLI — DMC if you're reading this, Hi!) You'll have to use the provided HTTP module.

在NativeScript中,不能使用[request](https://github.com/request/request)类的库。 (这恰好是CLI中使用的库Particle自己的DMC-如果您正在阅读,则为DMC,嗨!)您必须使用提供的HTTP模块。

If you scroll all the way to the bottom of that page, you'll see a fully fledged POST example. I'll reproduce it here but with some Particle specific changes:

如果您一直滚动到该页面底部 ,将会看到一个完整的POST示例。 我将在此处重现它,但会进行一些特定于粒子的更改:

// Create form post data
var data = new FormData();
data.append("name", "update");
data.append("data", "It's hammer time!");
data.append("private", "true");
data.append("access_token", _token);

// Configure the httpModule
return httpModule
    .request({
        url: `https://api.particle.io/v1/devices/events`,
        method: "POST",
        content: data
    })
    .then(
        response => {
            const result = response.content.toJSON();
            console.log(result);
        },
        e => {
            if (e) console.log(e);
        }
    );

The above is an example of what's equivalent to Particle.publish in DeviceOS. Let's break down the parts.

上面是与DeviceOS中的Particle.publish等效的示例。 让我们分解零件。

First of all, one of the main gotchas of Particle's Web API is the data format. I first expected that they use JSON but I was sorely wrong. After actually reading the documentation I realized that most POST requests were actually application/x-www-form-urlencoded. That means when you submit data, it's the equivalent to hitting the submit button on an HTML form.

首先,粒子Web API的主要难题之一是数据格式。 我最初希望他们使用JSON,但是我非常错误。 实际阅读文档后,我意识到大多数POST请求实际上都是application/x-www-form-urlencoded 。 这意味着您提交数据时,相当于单击HTML表单上的“提交”按钮。

Fortunately, there is an easy way to assemble form data in Node/JavaScript. We can use the FormData() object. Take a look at the above. There should be some familiar parameter names in the data.append calls.

幸运的是,有一种简单的方法可以在Node / JavaScript中组装表单数据。 我们可以使用FormData()对象。 看看上面的内容。 data.append调用中应该有一些熟悉的参数名称。

"name" refers to the name of the event you're publishing to.

"name"是指您要发布到的事件的名称。

"data" refers to the string formatted data that you're publishing.

"data"是指您要发布的字符串格式的数据。

"private" dictates whether or not you want to broadcast this data to the whole Particle world, or just your little corner of it.

"private"指示您是否要将此数据广播到整个粒子世界,或者只是广播到您的小角落。

"access_token" is a token that you can generate in order to make these API calls. Without a token though, you're dead in the water.

"access_token"是可以生成以进行这些API调用的令牌。 如果没有令牌,您将死在水里。

获取令牌 (Getting a Token)

Where do we get this elusive access_token?

我们从哪里得到这个难以捉摸的access_token

At first I had no idea.

起初我不知道。

I created an OAuth user and secret in the console. That lead to a dead end. Fiddled around with different API calls and settings. Nothing. Then it hit me like a ton of bricks. There's an access_token attached to the curl request on every device page!

我在控制台中创建了OAuth用户和密码。 那导致死胡同。 摆弄着不同的API调用和设置。 没有。 然后它像一堆砖头一样打击我。 每个设备页面上的curl请求都有一个access_token

Open up any device, click the little console button near Events. A popup with instructions an a URL will pop up. Copy the text after access_token=. That is your access_token! See below:

打开任何设备,单击“ 事件”附近的小控制台按钮 带有说明和URL的弹出窗口将会弹出。 在access_token=之后复制文本。 那就是你的access_token ! 见下文:

You can use this token to make calls to the Particle API. This can be to subscribe, publish, write to a function, read variables and more.

您可以使用此令牌来调用Particle API。 这可以是订阅,发布,写入函数,读取变量等。

通过命令行 (Through the command line)

That's nice and everything but how the heck can you programmatically generate one? One way is with the command line.

很好,一切都很好,但是您如何以编程方式生成一个呢? 一种方法是使用命令行。

particle token create is the name of the command you need to know about. When you run it, you'll be prompted to login. (Also enter your Authenticator code if you use one.) Then the command line will spit out a shiny new access_token you can use with the API!

particle token create是您需要了解的命令的名称。 运行它时,系统将提示您登录。 (如果您使用的话,也请输入您的Authenticator代码。)然后,命令行将吐出一个可用于API的闪亮的新access_token

通过API本身 (Through the API itself)

If you couldn't guess, particle token create is a frontend to a raw API call. You can make these API calls directly too. Here's what it looks like in NativeScript.

如果您无法猜测, particle token create就是原始API调用前端 。 您也可以直接进行这些API调用。 这是NativeScript中的样子。

// Create form post data
var data = new FormData();
data.append("username", "jaredwolff");
data.append("password", "this is not my password");
data.append("grant_type", "password");
data.append("client_name", "user");
data.append("client_secret", "client_secret_here");

// Configure the httpModule
return httpModule
    .request({
        url: `https://api.particle.io/v1/oauth/token`,
        method: "POST",
        content: data
    })
    .then(
        response => {
            const result = response.content.toJSON();
            console.log(result);
        },
        e => {
            if (e) console.log(e);
        }
    );

This call may get more complicated. Mostly in the case if you have two factor authorization setup. It's well worth it when you figure it all out. After all, no one wants to manually create auth tokens if they don't have to!

该调用可能变得更加复杂。 通常,如果您有两个因素的授权设置。 当您全力以赴时,这是非常值得的。 毕竟,没有人愿意手动创建身份验证令牌!

Now you're ready to write and read from your devices. There's one thing though that may trip you up. Subscribing to events can be troublesome with a regular HTTP client. So much so that if you try to do it with NativeScript's HTTP client, it will lock up and never return. Luckily there is a way to handle these special HTTP calls.

现在,您可以进行设备读写了。 虽然有一件事可能会使您绊倒。 对于常规HTTP客户端,订阅事件可能会很麻烦。 如此之多,以至于如果您尝试使用NativeScript的HTTP客户端执行此操作,它将锁定并且永远不会返回。 幸运的是,有一种方法可以处理这些特殊的HTTP调用。

服务器发送了什么? (Server Sent What?)

Server Sent Events (SSE for short) is an HTTP/S subscription functionality. It allows you to connect to a SSE end point and continuously listen for updates. It's a similar web technology to what companies use for push notifications. It does require some extra functionality under the hood though...

服务器发送事件(简称SSE)是HTTP / S订阅功能。 它使您可以连接到SSE端点并持续监听更新。 这与公司用于推送通知的网络技术类似。 尽管它确实需要一些额外的功能...

上证所图书馆 (SSE Library)

After much head scratching and searching I stumbled upon nativescript-sse. It looked simple enough that I could start using immediately. More problems arose when I tried to use it though.

经过nativescript-sse和搜寻之后,我偶然发现了nativescript-sse 。 它看起来很简单,我可以立即开始使用。 但是,当我尝试使用它时,出现了更多问题。

First, it turns out you can't use the library in tns preview mode. The alternative is to use tns run ios --emulator or use tns run ios with your iPhone connected to your computer. The non-emulator command will automatically deliver your prototype app.

首先,事实证明您不能在tns preview模式下使用该库。 替代方法是在连接了iPhone的计算机上使用tns run ios --emulator或使用tns run ios 。 non-emulator命令将自动提供您的原型应用程序。

Side note: I had already set up my phone in Xcode. You may have to do this yourself before tns run ios is able to find and deploy to your phone.

旁注:我已经用Xcode设置了手机。 在tns run ios能够找到并部署到手机之前,您可能必须自己执行此操作。

Secondly, once I got the library working, I noticed I would get some very nasty errors. The errors seemed to happen whenever a new message from Particle came along.

其次,一旦我的图书馆开始工作,我注意到我会遇到一些非常讨厌的错误。 每当来自Particle的新消息出现时,错误似乎就会发生。

Turns out the underlying Swift library for iOS had fixed this last year. So I took it upon myself to figure out how to upgrade the NativeScript plugin. I'll save you the time to say that it can be a pain and there is a learning curve!

事实证明,iOS的基础Swift库已于去年修复。 因此,我亲自思考了如何升级NativeScript插件。 我会节省您的时间,说这可能很痛苦,而且有学习的弯路!

Fortunately after some hacking I got something working. More instructions on how to compile the plugin are in the README. Alternatively, you can download a pre-built one on the Release page of the repository.

幸运的是,经过一些黑客攻击后,我有了一些工作。 有关如何编译该插件的更多说明,请参见README 。 或者,您可以在存储库的“ 发行”页面上下载预构建的一个

Download the .tgz file to wherever you like. Then, you can add it using tns plugin add. The full command looks like this:

.tgz文件下载到.tgz位置。 然后,您可以使用tns plugin add添加它。 完整的命令如下所示:

tns plugin add path/to/plugin/file.tgz

You can check to make sure the library is installed by running tns plugin list

您可以通过运行tns plugin list来检查以确保已安装该库

**jaredwolff$ tns plugin list
Dependencies:
┌─────────────────────┬──────────────────────────────────────────────────────────────────────────────────┐
│ Plugin              │ Version                                                                          │
│ @nativescript/theme │ ~2.2.1                                                                           │
│ nativescript-sse    │ file:../../Downloads/nativescript-sse/publish/package/nativescript-sse-4.0.3.tgz │
│ tns-core-modules    │ ~6.3.0                                                                           │
└─────────────────────┴──────────────────────────────────────────────────────────────────────────────────┘
Dev Dependencies:
┌──────────────────────────┬─────────┐
│ Plugin                   │ Version │
│ nativescript-dev-webpack │ ~1.4.0  │
│ typescript               │ ~3.5.3  │
└──────────────────────────┴─────────┘
NOTE:
If you want to check the dependencies of installed plugin use npm view <pluginName> grep dependencies
If you want to check the dev dependencies of installed plugin use npm view <pluginName> grep devDependencies**

Once installed, invoking the library takes a few steps. Here's an example:

安装完成后,调用库需要几个步骤。 这是一个例子:

import { SSE } from "nativescript-sse";

sse = new SSE(
            "https://api.particle.io/v1/events/blob?access_token=<your access token>",
            {}

// Add event listener
sse.addEventListener("blob");

// Add callback
sse.events.on("onMessage", data=>{
	// TODO: do stuff with your event data here!
	console.log(data);
});

// Connect if not already
sse.connect();

First you need to import and create an instance of the library. When you create the instance, you will have to enter the URL that you want to use.

首先,您需要导入并创建该库的实例。 创建实例时,必须输入要使用的URL。

In this case we'll be doing the equivalent of Particle.subscribe(). It should look something similar to the above: https://api.particle.io/v1/events/<your event name>?access_token=<your access token>.

在这种情况下,我们将等效于Particle.subscribe() 。 它看起来应该类似于上面的内容: https://api.particle.io/v1/events/<your event name>?access_token=<your access token> : https://api.particle.io/v1/events/<your event name>?access_token=<your access token>

Replace <your event name> and <your access token> with the name of your event and your freshly created token!

<your event name><your access token>替换为事件的名称和您新创建的令牌!

Then you set up the library to listen for the event you care about. In this case blob is the event I most care about.

然后,您设置库以侦听您关心的事件。 在这种情况下, blob是我最关心的事件。

Then make sure you configure a callback! That way you can get access to the data when blob does come along. I've made a TODO note where you can access said data.

然后确保您配置了回调! 这样一来,当出现blob时,您就可以访问数据。 我做了一个TODO记录,您可以在其中访问所述数据。

Finally, you can connect using the .connect() method. If you don't connect, SSE will not open a session and you'll get no data from Particle.

最后,您可以使用.connect()方法进行连接。 如果您不连接,SSE将不会打开会话,您也不会从Particle中获取任何数据。

Placement of the code is up to you but from the examples it looks like within the constructor() of your model is a good place.(https://github.com/jaredwolff/nativescript-sse/blob/master/demo/app/main-view-model.ts)

代码的位置由您决定,但是从示例看来,在模型的constructor()中看起来是个好地方。( https://github.com/jaredwolff/nativescript-sse/blob/master/demo/app /main-view-model.ts )

其他例子 (Other Examples)

If you're curious how to use SSE in other places I have another great example: Particle's CLI.

如果您想知道如何在其他地方使用SSE,我还有另一个很好的例子:Particle的CLI。

Particle uses the [request](https://github.com/request/request) library to handle SSE events in the app. Whenever you call particle subscribe blob it invokes a getStreamEvent further inside the code.  You can check it out here. The request library has more information on streaming here.

粒子使用[request](https://github.com/request/request)库处理应用程序中的SSE事件。 每当您调用particle subscribe blob它都会在代码内部进一步调用getStreamEvent 。 您可以在这里查看。 request库在此处提供有关流式传输的更多信息。

更多资源 (More resources)

This is but the tip of the iceberg when it comes to connecting with Particle's API. Particle has some great documentation (as always) you can check out. Here are some important links:

这只是与Particle的API连接时的冰山一角。 粒子有一些很棒的文档(一如既往),您可以签出。 以下是一些重要的链接:

结论 (Conclusion)

In this post we've talked about app frameworks, NativeScript, NativeScript plugins and Server Sent Events. Plus all the Particle related things so you can connect your NativeScript app to Particle's API.

在本文中,我们讨论了应用程序框架,NativeScript,NativeScript插件和服务器发送事件。 加上所有与Particle相关的东西,以便您可以将NativeScript应用程序连接到Particle的API。

I hope you've found this quick tutorial useful. If you have any questions feel free to leave a comment or send me a message. Also be sure to check out my newly released guide. It has content just like this all about Particle's ecosystem.

我希望您发现本快速教程对您有所帮助。 如果您有任何问题,请随时发表评论或给我发送消息 。 另外,请务必查看我最新发布的指南 。 它具有与粒子生态系统一样的内容。

Until next time!

直到下一次!

This post was originally from https://www.jaredwolff.com/how-to-develop-particle-iot-apps-using-nativescript/

这篇文章最初来自 https://www.jaredwolff.com/how-to-develop-particle-iot-apps-using-nativescript/

翻译自: https://www.freecodecamp.org/news/how-to-develop-particle-iot-apps-using-nativescript/

粒子滤波 应用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值