intdashを支えるテクノロジー
intdashのAPIにアクセスするための各種クライアントライブラリをご提供いたします。
intdashが持つ各種リソースへのアクセスには、REST APIを使用します。REST APIについては、OpenAPI形式で記載されたAPIドキュメントをご提供いたします。OpenAPIの各種ツールを使用することで、様々な言語向けのクライアントライブラリを自動生成してご利用いただけます。
import apiclient
from apiclient.api import auth_me_api
URL_API = "https://example.intdash.jp"
API_TOKEN = "xxxxxxxxxx"
if __name__ == "__main__":
configuration = apiclient.Configuration(
host=f"{URL_API}/api",
api_key={"IntdashToken": API_TOKEN},
)
with apiclient.ApiClient(configuration) as client:
api_instance = auth_me_api.AuthMeApi(client)
try:
me = api_instance.get_me()
print(f"Hello {me.name}")
except apiclient.ApiException as e:
print(e)
import { AuthMeApi } from "intdash";
const URL_API = "https://example.intdash.jp";
const API_TOKEN = "xxxxxxxxxx";
const authMeApi = new AuthMeApi({ isJsonMime: () => true }, `${URL_API}/api`);
const getMe = async () => {
try {
const { data: me } = await authMeApi.getMe({
headers: { "X-Intdash-Token": API_TOKEN },
});
console.log(`Hello ${me.name}`);
} catch (error) {
console.error(error);
}
};
getMe();
import intdash
let urlAPI = "https://example.intdash.jp"
let apiToken = "xxxxxxxxxx"
intdashAPI.basePath = urlAPI + "/api"
intdashAPI.customHeaders["X-Intdash-Token"] = apiToken
var group = DispatchGroup()
group.enter()
AuthMeAPI.getMe(apiResponseQueue: .global()) { me, error in
defer { group.leave() }
guard let me = me else {
print(error?.localizedDescription ?? "")
return
}
print("Hello \(me.name)")
}
group.wait()
using intdash.Api;
using intdash.Client;
const string URL_API = "https://example.intdash.jp";
const string API_TOKEN = "xxxxxxxxxx";
var apiConfig = new Configuration();
apiConfig.BasePath = URL_API + "/api";
apiConfig.AddApiKey("X-Intdash-Token", API_TOKEN);
try
{
var me = (new AuthMeApi(apiConfig)).GetMe();
Console.WriteLine($"Hello {me.Name}");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
package main
import (
"context"
"fmt"
"log"
intdash "path/to/autogenerated"
)
const (
urlAPI = "https://example.intdash.jp"
apiToken = "xxxxxxxxxx"
)
func main() {
cfg := intdash.NewConfiguration()
cfg.Servers = intdash.ServerConfigurations{{URL: fmt.Sprintf("%s/api", urlAPI)}}
cfg.DefaultHeader["X-Intdash-Token"] = apiToken
client := intdash.NewAPIClient(cfg)
ctx := context.Background()
me, _, err := client.AuthMeApi.GetMe(ctx).Execute()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Hello %s", me.Name)
}
use intdash::apis::{
auth_me_api::get_me,
configuration::{ApiKey, Configuration},
};
const URL_API: &str = "https://example.intdash.jp/api";
const API_TOKEN: &str = "xxxxxxxxxx";
#[tokio::main(flavor = "current_thread")]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut cfg = Configuration::new();
cfg.base_path = URL_API.to_string();
cfg.api_key = Some(ApiKey {
prefix: None,
key: API_TOKEN.to_string(),
});
let me = get_me(&cfg).await?;
println!("Hello {}", me.name);
Ok(())
}
intdashを用いたリアルタイム通信には、リアルタイムAPIを使用します。リアルタイムAPIについては、当社で実装したクライアントライブラリをご提供いたします。ライブラリ未提供の言語については、プロトコル仕様書のご提供も可能です。
import asyncio
import uuid
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
import iscp
URL_API = "https://example.intdash.jp"
ADDRESS = "example.intdash.jp:443"
NODE_ID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
NODE_SECRET = "xxxxxxxxxx"
async def main():
def token_source():
oauth = OAuth2Session(client=BackendApplicationClient(client_id=NODE_ID))
oauth.fetch_token(
token_url=f"{URL_API}/api/auth/oauth2/token",
client_id=NODE_ID,
client_secret=NODE_SECRET,
include_client_id=True,
)
return oauth.token["access_token"]
params = {
"address": ADDRESS,
"connector": iscp.WebSocketConnector(enable_tls=True),
"token_source": token_source,
"node_id": NODE_ID,
}
async with await iscp.Conn.connect(**params) as conn:
session_id = str(uuid.uuid4())
base_time = iscp.DateTime.utcnow()
async with await conn.open_upstream(session_id=session_id) as upstream:
for _ in range(10):
await asyncio.sleep(1)
now = iscp.DateTime.utcnow()
await upstream.write_data_points(
iscp.DataID(
name="greeting",
type="string",
),
iscp.DataPoint(
elapsed_time=now.unix_nano() - base_time.unix_nano(),
payload=b"hello",
),
)
if __name__ == "__main__":
asyncio.run(main())
import * as iscp from '@aptpod/iscp-ts'
import { AuthOAuth2Api } from 'intdash'
import { v4 as uuidV4 } from 'uuid'
const URL_API = 'https://example.intdash.jp'
const ADDRESS = 'example.intdash.jp:443'
const NODE_ID = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
const NODE_SECRET = 'xxxxxxxxxx'
const sleep = (milliseconds: number) => {
return new Promise((resolve) => setTimeout(resolve, milliseconds))
}
const getEpochNanoseconds = () => {
return BigInt(Date.now()) * BigInt(1e6)
}
const authOauthApi = new AuthOAuth2Api({
isJsonMime: () => true
}, `${URL_API}/api`)
const tokenSource = async () => {
const res = await authOauthApi.issueToken({
grantType: 'client_credentials',
clientId: NODE_ID,
clientSecret: NODE_SECRET,
})
return res.data.access_token
}
;(async () => {
const connector = new iscp.WebSocketConnector({
enableTLS: true,
})
const conn = await iscp.Conn.connect({
address: ADDRESS,
connector,
tokenSource,
nodeId: NODE_ID,
})
const sessionId = uuidV4()
const baseTime = getEpochNanoseconds()
const upstream = await conn.openUpstream({
sessionId,
})
for (let i = 0; i < 10; i++) {
await sleep(1000)
const dataId = new iscp.DataId({
name: 'greeting',
type: 'string',
})
const dataPoint = new iscp.DataPoint({
elapsedTime: getEpochNanoseconds() - baseTime,
payload: new TextEncoder().encode('hello'),
})
await upstream.writeDataPoints(dataId, [dataPoint])
}
await upstream.close()
await conn.close()
})()
import intdash
import iSCP
let urlAPI = "https://example.intdash.jp"
let address = "example.intdash.jp"
let nodeID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
let nodeSecret = "xxxxxxxxxx"
var group = DispatchGroup()
group.enter()
var tokenSource: (@escaping (String?) -> ()) -> () = { token in
intdashAPI.basePath = urlAPI + "/api"
AuthOAuth2API.issueToken(grantType: .clientCredentials,
clientId: nodeID,
clientSecret: nodeSecret,
apiResponseQueue: .global()) { data, error in
token(data?.accessToken)
}
}
Connection.connect(
address: address,
transportConfig: Transport.WebSocket.Config(enableTLS: true),
tokenSource: tokenSource,
nodeID: nodeID) { connection, error in
guard let connection = connection else {
print(error?.localizedDescription ?? "")
group.leave()
return
}
let sessionID = UUID().uuidString
let baseTime = Date().timeIntervalSince1970
connection.openUpstream(sessionID: sessionID) { upstream, error in
guard let upstream = upstream else {
print(error?.localizedDescription ?? "")
connection.close()
group.leave()
return
}
defer {
upstream.close()
connection.close()
group.leave()
}
for _ in 0..<10 {
Thread.sleep(forTimeInterval: 1.0)
let now = Date().timeIntervalSince1970
upstream.writeDataPoint(
dataID: DataID(
name: "greeting",
type: "string"
),
dataPoint: DataPoint(
elapsedTime: now - baseTime,
payload: "hello".data(using: .utf8)!
))
}
}
}
group.wait()
using intdash.Api;
using intdash.Client;
using iSCP;
using iSCP.Model;
using iSCP.Transport;
using System.Text;
const string URL_API = "https://example.intdash.jp";
const string ADDRESS = "example.intdash.jp";
const string NODE_ID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
const string NODE_SECRET = "xxxxxxxxxx";
var task = Task.Run(async () =>
{
var tokenSource = new Action<Action<string>>(async token =>
{
var apiConfig = new Configuration();
apiConfig.BasePath = URL_API + "/api";
var res = await new AuthOAuth2Api(apiConfig).IssueTokenAsync(
grantType: "client_credentials",
clientId: NODE_ID,
clientSecret: NODE_SECRET).ConfigureAwait(false);
token.Invoke(res.AccessToken);
});
var (connection, connectionError) = await Connection.ConnectAsync(
address: ADDRESS,
transportConfig: new WebSocket.Config(enableTls: true),
tokenSource: tokenSource,
nodeId: NODE_ID).ConfigureAwait(false);
if (connectionError != null)
{
Console.WriteLine(connectionError);
return;
}
try
{
var sessionId = Guid.NewGuid().ToString();
var baseTime = DateTime.UtcNow.Ticks;
var (upstream, upstreamError) = await connection.OpenUpstreamAsync(sessionId).ConfigureAwait(false);
if (upstreamError != null)
{
Console.WriteLine(upstreamError);
return;
}
try
{
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1 * 1000);
var now = DateTime.UtcNow.Ticks;
upstream.WriteDataPoint(
dataId: new DataId(
name: "greeting",
type: "string"),
dataPoint: new DataPoint(
elapsedTime: now - baseTime,
payload: Encoding.UTF8.GetBytes("hello"))
);
}
}
finally
{
upstream.Close();
}
}
finally
{
connection.Close();
}
});
task.Wait();
package main
import (
"context"
"log"
"time"
"github.com/aptpod/iscp-go/iscp"
"github.com/aptpod/iscp-go/message"
"github.com/aptpod/iscp-go/transport/websocket"
"github.com/google/uuid"
"golang.org/x/oauth2/clientcredentials"
)
const (
urlAPI = "https://example.intdash.jp"
address = "example.intdash.jp:443"
nodeID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
nodeSecret = "xxxxxxxxxx"
)
func main() {
ctx := context.Background()
c := clientcredentials.Config{
ClientID: nodeID,
ClientSecret: nodeSecret,
TokenURL: fmt.Sprintf("%s/api/auth/oauth2/token", urlAPI),
}
tokenSource := c.TokenSource(ctx)
conn, err := iscp.Connect(
address,
iscp.TransportName("websocket"),
iscp.WithConnWebSocket(websocket.DialerConfig{
Path: "/api/iscp/connect",
EnableTLS: true,
}),
iscp.WithConnTokenSource(iscp.TokenSourceFunc(func() (iscp.Token, error) {
token, err := tokenSource.Token()
if err != nil {
return "", err
}
return iscp.Token(token.AccessToken), nil
})),
iscp.WithConnNodeID(nodeID),
)
if err != nil {
log.Fatal(err)
}
defer conn.Close(ctx)
sessionUUID := uuid.New()
baseTime := time.Now()
upstream, err := conn.OpenUpstream(ctx, sessionUUID.String())
if err != nil {
log.Fatal(err)
}
defer upstream.Close(ctx)
for i := 0; i < 10; i++ {
time.Sleep(time.Second)
dataID := message.DataID{
Name: "greeting",
Type: "string",
}
dataPoint := message.DataPoint{
ElapsedTime: time.Since(baseTime),
Payload: []byte("hello"),
}
if err := upstream.WriteDataPoints(ctx, &dataID, &dataPoint); err != nil {
log.Fatal(err)
}
}
}
use oauth2::basic::BasicClient;
use oauth2::reqwest::async_http_client;
use oauth2::{AuthType, AuthUrl, ClientId, ClientSecret, TokenResponse, TokenUrl};
use std::{sync::Arc, time::Duration};
use tokio::runtime::Runtime;
const URL_API: &str = "https://example.intdash.jp";
const ADDRESS: &str = "example.intdash.jp";
const NODE_ID: &str = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
const NODE_SECRET: &str = "xxxxxxxxxx";
#[derive(Clone)]
struct TokenSource {
node_id: String,
client_secret: String,
url_api: String,
}
#[async_trait::async_trait]
impl iscp::TokenSource for TokenSource {
async fn token(&self) -> iscp::error::Result<String> {
let client = BasicClient::new(
ClientId::new(self.node_id.to_string()),
Some(ClientSecret::new(self.client_secret.to_string())),
AuthUrl::new(format!("{}/api/auth/oauth2/authorization", self.url_api)).unwrap(),
Some(TokenUrl::new(format!("{}/api/auth/oauth2/token", self.url_api)).unwrap()),
);
let client = client.set_auth_type(AuthType::RequestBody);
let token_result = client
.exchange_client_credentials()
.request_async(async_http_client)
.await;
Ok(token_result.unwrap().access_token().secret().clone())
}
}
fn main() {
let token = Arc::new(TokenSource {
node_id: NODE_ID.to_string(),
client_secret: NODE_SECRET.to_string(),
url_api: URL_API.to_string(),
});
let builder = iscp::ConnBuilder::new(ADDRESS, iscp::TransportKind::WebSocket)
.websocket_config(Some(iscp::tr::WebSocketConfig {
path: "/api/iscp/connect".to_string(),
enable_tls: true,
..Default::default()
}))
.encoding(iscp::enc::EncodingKind::Proto)
.token_source(Some(token))
.node_id(NODE_ID);
Runtime::new().unwrap().block_on(async {
let conn = builder.connect().await.unwrap();
let session_id = uuid::Uuid::new_v4().to_string();
let base_time = chrono::Utc::now();
let up = conn
.upstream_builder(&session_id)
.flush_policy(iscp::FlushPolicy::IntervalOnly {
interval: std::time::Duration::from_millis(5),
})
.ack_interval(chrono::Duration::milliseconds(1000))
.persist(true)
.close_timeout(Some(Duration::new(1, 0)))
.build()
.await
.unwrap();
for _ in 0..10 {
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
up.write_data_points(iscp::DataPointGroup {
id: iscp::DataId::new("greeting", "string"),
data_points: vec![iscp::DataPoint {
payload: "hello".into(),
elapsed_time: chrono::Utc::now() - base_time,
}],
})
.await
.unwrap();
}
up.close(Some(iscp::UpstreamCloseOptions {
close_session: true,
}))
.await
.unwrap();
conn.close().await.unwrap();
});
}
intdashに接続可能なデバイスを簡単に開発するためデバイス開発キットをご提供いたします。エージェントソフトウェアをインストールして接続プラグインを開発するだけで、お好きなデバイスをintdashに対応させることが可能です。
intdash Edge Agentは、intdash Terminal Systemでも使用されている、intdashとデータを送受信するためのネットワークエージェントソフトウェアです。intdashの特徴であるデータのリアルタイム伝送機能や完全回収の機能を、インストールするだけで利用できます。
intdash Edge Agent に様々なデバイスを接続するためのプラグイン機構です。所定のインターフェイスに沿ってプログラムを開発してデプロイするだけで、お客様の独自デバイスを簡単に接続することができます。