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

RI_SDK_connector_i2c_ReadBytes

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

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

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

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

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

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

  • Shared object
RI_SDK_connector_i2c_ReadBytes(descriptor, addr, buf, len, readBytesLen, errorText):errorCode
  • Golang gRPC
RI_SDK_Connector_I2C_ReadBytes(descriptor int64, addr uint8, len int64) (buf []byte, errorText string, errorCode int64, err error)

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

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

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

Параметр Тип для 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
readBytesLen *int (тип C) int64 Указатель на количество прочитанных байтов
errorText char[1000] (тип C) string Текст ошибки (передается как параметр, если происходит ошибка метод записывает в этот параметр текст ошибки)
errorCode int (тип C) int64 Код ошибки

Примеры

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

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

  • Python
# Чтение массива из 16 байт с i2c адаптера по адресу 0x40 
b = c_ulonglong()
errCode = lib.RI_SDK_connector_i2c_ReadBytes(descriptor, 0x40, b, 16, readBytesLen, errTextC)
if errCode != 0:
    print(errCode, errTextC.raw.decode())
    sys.exit(2)
# Конвертируем полученное значение c_ulonglong в массив байт
buf = b.value.to_bytes(readBytesLen.value, "little")
print("read bytes len : ", readBytesLen.value)
print("read bytes: ", buf)
    
  • C
// Запись массива байт buf на i2c адаптер по адресу 0x40
unsigned long long b;
errCode = RI_SDK_connector_i2c_ReadBytes(descriptor, 0x40, &b, 16, &readBytesLen, errorText);
if (errCode != 0) {
    printf("errorText:%s\n", errorText);
    return errCode;
}

printf("read bytes len: %d\n", readBytesLen);

// Конвертируем полученное значение c_ulonglong в массив байт и выводим
char buf[readBytesLen];
itoa(b, buf, 10);
printf("read bytes: ");
for (int i = 0; i < readBytesLen; i++) {
    printf(" %d", buf[i]);
}
printf("\n");
  • C++
// Запись массива байт buf на i2c адаптер по адресу 0x40
unsigned long long b;
errCode = RI_SDK_connector_i2c_ReadBytes(descriptor, 0x40, &b, 16, &readBytesLen, errorText);
if (errCode != 0) {
    printf("errorText:%s\n", errorText);
    return errCode;
}

printf("read bytes len: %d\n", readBytesLen);

// Конвертируем полученное значение c_ulonglong в массив байт и выводим
char buf[readBytesLen];
itoa(b, buf, 10);
printf("read bytes: ");
for (int i = 0; i < readBytesLen; i++) {
    printf(" %d", buf[i]);
}
printf("\n");    
  • Golang
// Чтение массива из 16 байт с i2c адаптера по адресу 0x40
b := C.ulonglong(0)
errCode = C.RI_SDK_connector_i2c_ReadBytes(descriptor, 0x40, &b, 16, &readBytesLen, &errorTextC[0])
if errCode != 0 {
    fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
    return
}

fmt.Println("read bytes len: ", readBytesLen)

// Конвертируем полученное значение c_ulonglong в массив байт и выводим
var readBuffer = make([]byte, 0)
ptr := uintptr(b)
for i := 0; i < int(readBytesLen); i++ {
    value := *(*byte)(unsafe.Pointer(ptr))
    readBuffer = append(readBuffer, value)
    ptr = ptr + 1
}

fmt.Printf("read bytes: %d\n", readBuffer)
  • Golang gRPC
// Чтение массива из 16 байт с i2c адаптера по адресу 0x40
buf, errorText, errCode, err = client.RoboSdkApi.RI_SDK_Connector_I2C_ReadBytes(descriptor, 0x40, 16)
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("read bytes len: ", len(buf))
fmt.Println("read bytes: ", buf)
  • PHP
// Чтение массива из 16 байт с i2c адаптера по адресу 0x40 
$errCode = $ffi->RI_SDK_connector_i2c_ReadBytes($descriptor->cdata, 0x40, FFI::addr($b), 16, FFI::addr($readBytesLen), $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("Bytes read len: ". $readBytesLen . "\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_ReadBytes.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()
    readBytesLen = c_int()
    
    # Инициализация библиотеки 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)
    
    # Чтение массива из 16 байт с i2c адаптера по адресу 0x40 
    b = c_ulonglong()
    errCode = lib.RI_SDK_connector_i2c_ReadBytes(descriptor, 0x40, b, 16, readBytesLen, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)
    # Конвертируем полученное значение c_ulonglong в массив байт
    buf = b.value.to_bytes(readBytesLen.value, "little")
    print("read bytes len : ", readBytesLen.value)
    print("read bytes: ", buf)

    # Закрытие соединения 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, readBytesLen; 
    
    // Инициализация библиотеки 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 long long b;
    errCode = RI_SDK_connector_i2c_ReadBytes(descriptor, 0x40, &b, 16, &readBytesLen, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }
    
    printf("read bytes len: %d\n", readBytesLen);

    // Конвертируем полученное значение c_ulonglong в массив байт и выводим
    char buf[readBytesLen];
    itoa(b, buf, 10);
    printf("read bytes: ");
    for (int i = 0; i < readBytesLen; i++) {
        printf(" %d", buf[i]);
    }
    printf("\n");
    
    printf("Success");
    return 0;
}
  • C++
#include <stdbool.h>
#include "./librisdk.h" // Подключение библиотеки

int main(){

    char errorText[1000]; // текст ошибки. Передается как входной параметр,при возникновении ошибки в эту переменную будет записан текст ошибки
    int errCode; //код ошибки
    int descriptor, readBytesLen;
    
    // Инициализация библиотеки 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 long long b;
    errCode = RI_SDK_connector_i2c_ReadBytes(descriptor, 0x40, &b, 16, &readBytesLen, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }
    
    printf("read bytes len: %d\n", readBytesLen);

    // Конвертируем полученное значение c_ulonglong в массив байт и выводим
    char buf[readBytesLen];
    itoa(b, buf, 10);
    printf("read bytes: ");
    for (int i = 0; i < readBytesLen; i++) {
        printf(" %d", buf[i]);
    }
    printf("\n");
    
    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
    readBytesLen C.int
)

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
    }

    // Чтение массива из 16 байт с i2c адаптера по адресу 0x40
    b := C.ulonglong(0)
    errCode = C.RI_SDK_connector_i2c_ReadBytes(descriptor, 0x40, &b, 16, &readBytesLen, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    fmt.Println("read bytes len: ", readBytesLen)

    // Конвертируем полученное значение c_ulonglong в массив байт и выводим
    var readBuffer = make([]byte, 0)
    ptr := uintptr(b)
    for i := 0; i < int(readBytesLen); i++ {
        value := *(*byte)(unsafe.Pointer(ptr))
        readBuffer = append(readBuffer, value)
        ptr = ptr + 1
    }

    fmt.Printf("read bytes: %d\n", readBuffer)

    // Закрытие соединения 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
    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
    }

    // Чтение массива из 16 байт с i2c адаптера по адресу 0x40
    buf, errorText, errCode, err = client.RoboSdkApi.RI_SDK_Connector_I2C_ReadBytes(descriptor, 0x40, 16)
    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("read bytes len: ", len(buf))
    fmt.Println("read bytes: ", buf)

    // Закрытие соединения 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);
$readBytesLen = $ffi->new("int", 0);
$b = $ffi->new('unsigned long long', 0);

// Инициализация библиотеки 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;
}

// Чтение массива из 16 байт с i2c адаптера по адресу 0x40 
$errCode = $ffi->RI_SDK_connector_i2c_ReadBytes($descriptor->cdata, 0x40, FFI::addr($b), 16, FFI::addr($readBytesLen), $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("Bytes read len: ". $readBytesLen . "\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");

?>

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

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

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

Навигация

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