laurencehr / ubidots

连接到 ubidots.com api 版本 1.6 的客户端。

dev-master 2015-08-19 22:52 UTC

This package is not auto-updated.

Last update: 2024-09-18 10:33:27 UTC


README

Ubidots PHP API 客户端会对 Ubidots Api 进行调用。

安装

使用 Composer 安装

php 的 Ubidots 可通过 Composer 安装

{
    "require": {
        "ubidots/ubidots": "dev-master"
    }
}

连接到 API

在玩弄 API 之前,您应该使用您的私有 API 密钥连接到它,该密钥可以在您的 个人资料 中找到。

如果您还没有账户,您可以在 这里 创建一个。

一旦您有了 API 密钥,您可以通过创建一个 ApiClient 实例来连接到 API。假设您的 API 密钥是:"7fj39fk3044045k89fbh34rsd9823jkfs8323"。那么您的代码将如下所示

require 'vendor/autoload.php';

$api = new Ubidots\ApiClient($apikey="7fj39fk3044045k89fbh34rsd9823jkfs8323");

现在您有一个 ApiClient 实例 ("api"),可以用来连接到 Ubidots API。

保存新的值到变量中

检索要保存值的目标变量

$my_variable = $api->get_variable('56799cf1231b28459f976417');

给定已实例化的变量,您可以使用以下行保存一个新的值

$new_value = $my_variable->save_value( array('value'=>10) );

您也可以指定一个时间戳(可选)

$new_value = $my_variable->save_value( array('value'=>10, 'timestamp'=>1376061804407) );

如果没有指定时间戳,API 服务器将分配当前时间给它。我们认为您最好指定时间戳,这样记录就会反映值被捕获的确切时间,而不是到达我们服务器的时间。

创建数据源

如您现在所知,数据源表示生成时间序列数据的设备。

此行创建一个新的数据源

$new_datasource = $api->create_datasource( array("name"=>"myNewDs", "tags"=>array("firstDs", "new"), "description"=>"any des") );

'name' 键是必需的,但 'tags' 和 'description' 键是可选的。这个新的数据源可以用来跟踪不同的变量,所以让我们创建一个。

创建变量

变量是一个随时间包含不同值的时间序列。让我们创建一个

$my_variable = $new_datasource->create_variable( array("name"=>"myNewVar", "unit"=>"Nw") );

'name' 和 'unit' 键是必需的。

获取值

要获取变量的值,请在 Variable 类的实例中使用 get_values 方法。这将返回一个值数组。

如果您只想获取最后的 N 个值,请调用带有所需元素数量的方法。

/*
 * Getting all the values from the server. Note that this could result in a
 * lot of requests, and potentially violate your requests per second limit.
 */
$all_values = $new_variable->get_values();

/* If you want just the last 100 values you can use: */
$some_values = $new_variable->get_values(100);

获取数据源组

如果您想获取所有数据源,可以直接在 ApiClient 实例上调用一个方法。此方法返回一个对象 Datasource 数组。

/* Get all datasources */
$all_datasources = $api->get_datasources();

/* Get the last five created datasources */
$some_datasources = $api->get_datasources(5);

获取特定数据源

每个数据源都有一个 ID。可以通过此 ID 从服务器检索特定数据源。

例如,如果数据源的 ID 是 51c99cfdf91b28459f976414,可以按照以下方式检索

$my_specific_datasource = $api->get_datasource('51c99cfdf91b28459f976414');

从数据源获取变量组

您也可以检索数据源的一些或所有变量

/* Get all variables */
$all_variables =  $my_datasource->get_variables();

/* Get last 10 variables */
$some_variables =  $my_datasource->get_variables(10)

获取特定变量

与数据源一样,您可以使用变量的 ID 来检索有关它的详细信息

$my_specific_variable = $api->get_variable('56799cf1231b28459f976417');