Программирование на Blockly
Документация по RoboIntellect SDK (RI SDK)
Функциональный RI SDK API исполнительных устройств

RI_SDK_connector_i2c_WriteBytes

!!! ИНФОРМАЦИЯ

RI_SDK - библиотека Robo Intellect Software Development Kit

connector - название группы устройств коннекторов

i2c - название устройства i2c адаптера

WriteBytes - название метода записи массива байт по указанному адресу

Сигнатура функции

  • Shared object
RI_SDK_connector_i2c_WriteBytes(descriptor, addr, buf, len, wroteBytesLen, errorText):errorCode
  • Golang gRPC
RI_SDK_Connector_I2C_WriteBytes(descriptor int64, addr uint8, buf []byte, len int) (wroteBytesLen int64, errorText string, errorCode int64, err error)

Описание метода

Записывает len байтов из buf через i2c адаптера по адресу addr

Длина массива байт buf должна быть раной len

Параметры и возвращаемые значения

Параметр Тип для Shared object Тип для Golang gRPC Описание
descriptor int (тип C) int64 Дескриптор компонента, в котором будет производиться запись
addr uint8_t (тип C) uint8 Адрес, по которому будет производиться запись
buf *long long unsigned[len] (тип C) []byte Указатель на массив байт для записи
len int (тип C) int64 Длина массива buf
wroteBytesLen *int (тип C) int64 Указатель на количество записаных байтов
errorText char[1000] (тип C) string Текст ошибки (передается как параметр, если происходит ошибка метод записывает в этот параметр текст ошибки)
errorCode int (тип C) int64 Код ошибки

Примеры

Пример №1 - Запись массива байт buf на i2c адаптере по адресу 0x40

В данном примере осуществляется запись массива байт buf на i2c адаптере по адресу 0x40. Выводиться количество записанных байтов wroteBytesLength.

  • Python
    # Запись массива байт buf на i2c адаптер по адресу 0x40 
    # Перед записью конвертируем массив байт buf в тип c_ulonglong
    b = c_ulonglong(int.from_bytes(buf, "little"))
    errCode = lib.RI_SDK_connector_i2c_WriteBytes(descriptor, 0x40, b, len(buf), wroteBytesLen, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)
    
    print("wrote bytes : ", wroteBytesLen.value)
    
  • C
// Запись массива байт buf на i2c адаптер по адресу 0x40
unsigned char buf[5] = {10,0,0,244,1};
errCode = RI_SDK_connector_i2c_WriteBytes(descriptor, 0x40, (unsigned long long)buf, sizeof(buf)/sizeof(buf[0]), &wroteBytesLen, errorText);
if (errCode != 0) {
    printf("errorText:%s\n", errorText);
    return errCode;
}

printf("wrote bytes: %d\n", wroteBytesLen);
    
  • C++
// Запись массива байт buf на i2c адаптер по адресу 0x40
unsigned char buf[5] = {10,0,0,244,1};
errCode = RI_SDK_connector_i2c_WriteBytes(descriptor, 0x40, (unsigned long long)buf, sizeof(buf)/sizeof(buf[0]), &wroteBytesLen, errorText);
if (errCode != 0) {
    printf("errorText:%s\n", errorText);
    return errCode;
}

printf("wrote bytes: %d\n", wroteBytesLen);
    
  • Golang
// Запись массива байт buf на i2c адаптер по адресу 0x40
// Перед записью конвертируем массив байт buf в тип c_ulonglong
writeBuffer = append(writeBuffer, 10, 0, 0, 244, 1)
buf := (C.ulonglong)(uintptr(unsafe.Pointer(&writeBuffer[0])))
errCode = C.RI_SDK_connector_i2c_WriteBytes(descriptor, 0x40, buf, C.int(len(writeBuffer)), &wroteBytesLen, &errorTextC[0])
if errCode != 0 {
    fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
    return
}

fmt.Println("wrote bytes: ", wroteBytesLen)
  • Golang gRPC
// Запись массива байт buf на i2c адаптер по адресу 0x40
buf = append(buf, 10, 0, 0, 244, 1)
wroteBytesLen, errorText, errCode, err = client.RoboSdkApi.RI_SDK_Connector_I2C_WriteBytes(descriptor, 0x40, buf, len(buf))
if err != nil {
    fmt.Printf("gRPC Error: %v\n", err)
    return
}
if errCode != 0 {
    fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
    return
}

fmt.Println("wrote bytes: ", wroteBytesLen)
  • PHP
// Запись массива байт buf на i2c адаптер по адресу 0x40  
$errCode = $ffi->RI_SDK_connector_i2c_WriteBytes($descriptor->cdata, 0x40, $buf->cdata, 5, FFI::addr($wroteBytesLen), $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("wrote bytes: ". $wroteBytesLen . "\n");
Полный текст примера
  • Python

from ctypes.util import find_library
import platform
import sys
from ctypes import *

# Подключаем внешнюю библиотеку для работы с SDK
platform = platform.system()
if platform == "Windows":
    libName = "librisdk.dll"
if platform == "Linux":
    libName = "librisdk.so"

pathLib = find_library(libName)
lib = cdll.LoadLibrary(pathLib)


# Указываем типы аргументов для функций библиотеки RI_SDK
lib.RI_SDK_InitSDK.argtypes = [c_int, c_char_p]
lib.RI_SDK_CreateModelComponent.argtypes = [c_char_p, c_char_p, c_char_p, POINTER(c_int), c_char_p]
lib.RI_SDK_connector_i2c_Open.argtypes = [c_int, c_uint8, c_char_p]
lib.RI_SDK_connector_i2c_WriteBytes.argtypes = [c_int, c_uint8, POINTER(c_ulonglong), c_int, POINTER(c_int), c_char_p]
lib.RI_SDK_connector_i2c_Close.argtypes = [c_int, c_uint8, c_char_p]

def main():
    errTextC = create_string_buffer(1000)  # Текст ошибки. C type: char*
    descriptor = c_int()
    wroteBytesLen = c_int()
    buf = bytes([10,0,0,244,1])
    
    # Инициализация библиотеки RI SDK с уровнем логирования 3
    errCode = lib.RI_SDK_InitSDK(3, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    # Создание компонента i2c адаптера модели ch341
    errCode = lib.RI_SDK_CreateModelComponent("connector".encode(), "i2c_adapter".encode(), "ch341".encode(), descriptor, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    print("descriptor: ", descriptor.value)

    # Открытие соединения i2c адаптера по адресу 0x40
    errCode = lib.RI_SDK_connector_i2c_Open(descriptor, 0x40, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)
    
    # Запись массива байт buf на i2c адаптер по адресу 0x40 
    # Перед записью конвертируем массив байт buf в тип c_ulonglong
    b = c_ulonglong(int.from_bytes(buf, "little"))
    errCode = lib.RI_SDK_connector_i2c_WriteBytes(descriptor, 0x40, b, len(buf), wroteBytesLen, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)
    
    print("wrote bytes : ", wroteBytesLen.value)

    # Закрытие соединения i2c адаптера по адресу 0x40
    errCode = lib.RI_SDK_connector_i2c_Close(descriptor, 0x40, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    print("Success")

main()
 
 
  • C
#include "./librisdk.h" // Подключение библиотеки

int main(){

    char errorText[1000]; // текст ошибки. Передается как входной параметр,при возникновении ошибки в эту переменную будет записан текст ошибки
    int errCode; //код ошибки
    int descriptor, wroteBytesLen; 
    
    // Инициализация библиотеки RI SDK с уровнем логирования 3
    errCode = RI_SDK_InitSDK(3, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    // Создание компонента i2c адаптера модели ch341
    errCode = RI_SDK_CreateModelComponent("connector", "i2c_adapter", "ch341",  &descriptor, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }


    // Открытие соединения i2c адаптера по адресу 0x40
    errCode = RI_SDK_connector_i2c_Open(descriptor,  0x40, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }


    // Запись массива байт buf на i2c адаптер по адресу 0x40
    unsigned char buf[5] = {10,0,0,244,1};
    errCode = RI_SDK_connector_i2c_WriteBytes(descriptor, 0x40, (unsigned long long)buf, sizeof(buf)/sizeof(buf[0]), &wroteBytesLen, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("wrote bytes: %d\n", wroteBytesLen);

    // Закрытие соединения i2c адаптера по адресу 0x40
    errCode = RI_SDK_connector_i2c_Close(descriptor,  0x40, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("Success");
    return 0;
}
  • C++
#include <stdbool.h>
#include "./librisdk.h" // Подключение библиотеки

int main(){

    char errorText[1000]; // текст ошибки. Передается как входной параметр,при возникновении ошибки в эту переменную будет записан текст ошибки
    int errCode; //код ошибки
    int descriptor, wroteBytesLen;
    
    // Инициализация библиотеки RI SDK с уровнем логирования 3
    errCode = RI_SDK_InitSDK(3, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    // Создание компонента i2c адаптера модели ch341
    char connector[] = "connector";
    char i2cAdapter[] = "i2c_adapter";
    char ch341[] = "ch341";
    errCode = RI_SDK_CreateModelComponent(connector, i2cAdapter, ch341,  &descriptor, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("descriptor: %d\n", descriptor);

    // Открытие соединения i2c адаптера по адресу 0x40
    errCode = RI_SDK_connector_i2c_Open(descriptor,  0x40, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }


    // Запись массива байт buf на i2c адаптер по адресу 0x40
    unsigned char buf[5] = {10,0,0,244,1};
    errCode = RI_SDK_connector_i2c_WriteBytes(descriptor, 0x40, (unsigned long long)buf, sizeof(buf)/sizeof(buf[0]), &wroteBytesLen, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("wrote bytes: %d\n", wroteBytesLen);

    // Закрытие соединения i2c адаптера по адресу 0x40
    errCode = RI_SDK_connector_i2c_Close(descriptor,  0x40, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("Success");
    return 0;
}
  • Golang
package main

/*
#cgo CFLAGS: -I.
#cgo LDFLAGS: -L. -lrisdk
#include <librisdk.h> // Подключаем внешнюю библиотеку для работы с SDK.
*/
import "C"
import (
    "fmt"
    "unsafe"
)

var (
    errorTextC    [1000]C.char // Текст ошибки. C type: char*
    errCode       C.int        // Код ошибки. C type: int
    descriptor    C.int
    wroteBytesLen C.int
    writeBuffer   []byte
)

func main() {

    // Инициализация библиотеки RI SDK с уровнем логирования 3
    errCode = C.RI_SDK_InitSDK(3, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    // Создание компонента i2c адаптера модели ch341
    errCode = C.RI_SDK_CreateModelComponent(C.CString("connector"), C.CString("i2c_adapter"), C.CString("ch341"), &descriptor, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    fmt.Println("descriptor: ", descriptor)

    // Открытие соединения i2c адаптера по адресу 0x40
    errCode = C.RI_SDK_connector_i2c_Open(descriptor, 0x40, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    // Запись массива байт buf на i2c адаптер по адресу 0x40
    // Перед записью конвертируем массив байт buf в тип c_ulonglong
    writeBuffer = append(writeBuffer, 10, 0, 0, 244, 1)
    buf := (C.ulonglong)(uintptr(unsafe.Pointer(&writeBuffer[0])))
    errCode = C.RI_SDK_connector_i2c_WriteBytes(descriptor, 0x40, buf, C.int(len(writeBuffer)), &wroteBytesLen, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    fmt.Println("wrote bytes: ", wroteBytesLen)

    // Закрытие соединения i2c адаптера по адресу 0x40
    errCode = C.RI_SDK_connector_i2c_Close(descriptor, 0x40, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    fmt.Println("Success")

}
  • Golang gRPC
package main

import (
    "fmt"

    "github.com/rbs-ri/go-risdk"
)

var (
    client        *risdk.ClientRPC // Объект взяимодействия с API SDK
    errorText     string           // Текст ошибки
    errCode       int64            // Код ошибки
    err           error            // Ошибка gRPC
    descriptor    int64
    wroteBytesLen int64
    buf           []byte
)

func main() {

    // Открываем соединение для работы с API SDK по RPC
    client = risdk.GetClientRPC()

    // Закрываем соединение с RPC
    defer client.Client.Kill()

    // Инициализация библиотеки RI SDK с уровнем логирования 3
    errorText, errCode, err = client.RoboSdkApi.RI_SDK_InitSDK(3)
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    // Создание компонента i2c адаптера модели ch341
    descriptor, errorText, errCode, err = client.RoboSdkApi.RI_SDK_CreateModelComponent("connector", "i2c_adapter", "ch341")
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    fmt.Println("descriptor: ", descriptor)

    // Открытие соединения i2c адаптера по адресу 0x40
    errorText, errCode, err = client.RoboSdkApi.RI_SDK_Connector_I2C_Open(descriptor, 0x40)
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    // Запись массива байт buf на i2c адаптер по адресу 0x40
    buf = append(buf, 10, 0, 0, 244, 1)
    wroteBytesLen, errorText, errCode, err = client.RoboSdkApi.RI_SDK_Connector_I2C_WriteBytes(descriptor, 0x40, buf, len(buf))
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    fmt.Println("wrote bytes: ", wroteBytesLen)

    // Закрытие соединения i2c адаптера по адресу 0x40
    errorText, errCode, err = client.RoboSdkApi.RI_SDK_Connector_I2C_Close(descriptor, 0x40)
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    fmt.Println("Success")

}
  • PHP
<?php
// Подключаем внешнюю библиотеку для работы с SDK
$RELATIVE_PATH = '';
$headers = file_get_contents(__DIR__ . $RELATIVE_PATH . '/librisdk.h');
$headers = preg_replace(['/#ifdef __cplusplus\s*extern "C" {\s*#endif/i', '/#ifdef __cplusplus\s*}\s*#endif/i'], '', $headers);
$ffi = FFI::cdef($headers, __DIR__ . $RELATIVE_PATH . '/librisdk.dll');

$errorText = $ffi->new('char[1000]', 0); // Текст ошибки. Передается как входной параметр,при возникновении ошибки в эту переменную будет записан текст ошибки
$descriptor = $ffi->new('int', 0);
$pwm = $ffi->new('int', 0);
$wroteBytesLen = $ffi->new("int", 0);

$buf = $ffi->new("unsigned char[5]", 0);
$buf[0] = 10;
$buf[1] = 0;
$buf[2] = 0;
$buf[3] = 244;
$buf[4] = 1;

// Перед записью конвертируем массив байт buf в тип ulonglong
$buf = $ffi->cast("unsigned long long", FFI::addr($buf));

// Инициализация библиотеки RI SDK с уровнем логирования 3
$errCode = $ffi->RI_SDK_InitSDK(3, $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText) . " errCode: " . $errCode . " \n");
    return $errCode;
}

// Создание компонента i2c адаптера модели ch341
$errCode = $ffi->RI_SDK_CreateModelComponent("connector", "i2c_adapter", "ch341", FFI::addr($descriptor), $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("descriptor: " . $descriptor->cdata . "\n");

// Открытие соединения i2c адаптера по адресу 0x40
$errCode = $ffi->RI_SDK_connector_i2c_Open($descriptor->cdata, 0x40, $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

// Запись массива байт buf на i2c адаптер по адресу 0x40  
$errCode = $ffi->RI_SDK_connector_i2c_WriteBytes($descriptor->cdata, 0x40, $buf->cdata, 5, FFI::addr($wroteBytesLen), $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("wrote bytes: ". $wroteBytesLen . "\n");

// Закрытие соединения i2c адаптера по адресу 0x40
$errCode = $ffi->RI_SDK_connector_i2c_Close($descriptor->cdata, 0x40, $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("Success \n");

?>

29 просмотров0 комментариев

Комментарии (0)

Для участия в обсуждении вы должны быть авторизованным пользователем
Разделы
Программирование на Blockly
Документация по RoboIntellect SDK (RI SDK)
Функциональный RI SDK API исполнительных устройств

Навигация

ВойтиРегистрация