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

RI_SDK_sensor_VoltageSensor_Current

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

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

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

VoltageSensor - название устройства датчика тока, напряжения и мощности

Current - название метода получения значения силы тока

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

  • Golang DLL
RI_SDK_sensor_VoltageSensor_Current(descriptor, current, errorText):errorCode
  • Golang gRPC
RI_SDK_Sensor_VoltageSensor_Current(descriptor) (current float32, errorText string, errorCode int64, err error)

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

Получение значения силы тока в цепи.

Дает команду датчику тока , напряжения и мощности с дескриптором descriptor измерить силу тока в цепи, к которой подключен датчик. Записывает полученное значение в переменную current

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

Параметр Тип для Shared object Тип для Golang gRPC Описание
descriptor int (тип C) int64 Дескриптор компонента датчика тока, напряжения и мощности
current *float (тип C) float32 Указатель на значение силы тока (Ампер)
errorText char[1000] (тип C) string Текст ошибки (передается как параметр, если происходит ошибка метод записывает в этот параметр текст ошибки)
errorCode int (тип C) int64 Код ошибки

Примеры

Пример №1 - Измерение силы тока

В данном примере производится измерение силы тока, с помощью датчика с дескриптором voltageSensor. Сила тока записывается в переменную current, значение которой выводится в конце.

  • Python
# Получение значения силы тока
errCode = lib.RI_SDK_sensor_VoltageSensor_Current(voltageSensor, current, errTextC)
if errCode != 0:
    print(errCode, errTextC.raw.decode())
    sys.exit(2) 

print("current: ", current.value)
    
  • C
      // Получение значения силы тока
      errCode = RI_SDK_sensor_VoltageSensor_Current(sensorDescriptor, ¤t, errorText);
      if (errCode) {
      printf("errorText:%s\n", errorText);
      return errCode;
  }
  • C++
      // Получение значения силы тока
      errCode = RI_SDK_sensor_VoltageSensor_Current(sensorDescriptor, ¤t, errorText);
      if (errCode) {
      printf("errorText:%s\n", errorText);
      return errCode;
  }
  • Golang
        // Получение значения силы тока
        errCode = C.sensor_VoltageSensor_Current(sensorDescriptor, ¤t, &errorText[0])
        if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorText[0]))
        return
    }
  • Golang gRPC
      // Получение значения силы тока в цепи
      current, errText, errCode, err := client.RoboSdkApi.RI_SDK_Sensor_VoltageSensor_Current(inaSensorDescriptor)
      if errText != "" || errCode != 0 || err != nil {
      fmt.Printf("errText: %s; errCode:%d; err: %s", errText, errCode, err)
      return
  }
  • PHP
        // Получение значения силы тока
        $errCode = $ffi->RI_SDK_sensor_VoltageSensor_Current($sensorDescriptor->cdata, FFI::addr($current), $errorText);
        if ($errCode) {
        print("errorText:" . FFI::string($errorText) . " errCode: " . $errCode . " \n");
        return;
    }
Полный текст примера
  • 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_LinkVoltageSensorToController.argtypes = [c_int, c_int, c_uint8, c_char_p]
lib.RI_SDK_DestroySDK.argtypes = [c_bool, c_char_p]
lib.RI_SDK_sensor_VoltageSensor_Current.argtypes = [c_int, POINTER(c_float), c_char_p]

def main():
    errTextC = create_string_buffer(1000)  # Текст ошибки. C type: char*
    i2c = c_int()
    voltageSensor = c_int()
    current = c_float()

    # Инициализация библиотеки 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(), i2c, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    print("i2c: ", i2c.value)

    # Создание компонента датчика тока, напряжения и мощности модели ina219
    errCode = lib.RI_SDK_CreateModelComponent("sensor".encode(), "voltage_sensor".encode(), "ina219".encode(), voltageSensor, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    print("voltage_sensor: ", voltageSensor.value)

    # Связывание i2c с датчиком тока, напряжения и мощности
    errCode = lib.RI_SDK_LinkVoltageSensorToController(voltageSensor, i2c, 0x41, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)
  
  
    # Получение значения силы тока
    errCode = lib.RI_SDK_sensor_VoltageSensor_Current(voltageSensor, current, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2) 

    print("current: ", current.value) 

    # Удаление библиотеки со всеми компонентами
    errCode = lib.RI_SDK_DestroySDK(True, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    print("Success")

main()

  • C
      #include <stdlib.h>
      #include <stdio.h>
      #include <unistd.h>
      #include <string.h>
      #include <dlfcn.h>
      #include <stdint.h>

      int (*RI_SDK_InitSDK)(int logLevel, char *errorText);

      int (*RI_SDK_CreateModelComponent)(char *group, char *device, char *model, int *descriptor, char *errorText);

      int
      (*RI_SDK_LinkVoltageSensorToController)(int sensorDescriptor, int i2cAdapterDescriptor, uint8_t addr, char *errorText);

      int (*RI_SDK_sensor_VoltageSensor_Current)(int descriptor, float *result, char *errorText);

      int initLibrary() {
      void *handle;
      char *LIB_RISDK = getenv("LIB_RISDK");
      handle = dlopen(strcat(LIB_RISDK, "librisdk.so"), RTLD_NOW);
      if (!handle) {
      /* fail to load the library */
      fprintf(stderr, "Error: %s\n", dlerror());
      return -1;
  }

      *(void **) (&RI_SDK_InitSDK) = dlsym(handle, "RI_SDK_InitSDK");
      *(void **) (&RI_SDK_CreateModelComponent) = dlsym(handle, "RI_SDK_CreateModelComponent");
      *(void **) (&RI_SDK_LinkVoltageSensorToController) = dlsym(handle, "RI_SDK_LinkVoltageSensorToController");
      *(void **) (&RI_SDK_sensor_VoltageSensor_Current) = dlsym(handle, "RI_SDK_sensor_VoltageSensor_Current");
      return 0;
  }

      char errorText[1000]; // текст ошибки. Передается как входной параметр,при возникновении ошибки в эту переменную будет записан текст ошибки
      int sensorDescriptor;
      int i2cDescriptor;
      float current;

      int main() {
      int initErr;
      initErr = initLibrary();
      if (initErr != 0) {
      printf("fail to load init library");
      return initErr;
  }

      int errCode; //код ошибки

      // Инициализация библиотеки RI SDK
      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", &i2cDescriptor, errorText);
      if (errCode) {
      printf("errorText:%s\n", errorText);
      return errCode;
  }

      // Создание компонента датчика тока, напряжения и мощности модели ina219
      errCode = RI_SDK_CreateModelComponent("sensor", "voltage_sensor", "ina219", &sensorDescriptor, errorText);
      if (errCode) {
      printf("errorText:%s\n", errorText);
      return errCode;
  }

      // Связывание i2c с датчиком тока, напряжения и мощности
      errCode = RI_SDK_LinkVoltageSensorToController(sensorDescriptor, i2cDescriptor, 0x41, errorText);
      if (errCode) {
      printf("errorText:%s\n", errorText);
      return errCode;
  }

      // Получение значения силы тока
      errCode = RI_SDK_sensor_VoltageSensor_Current(sensorDescriptor, ¤t, errorText);
      if (errCode) {
      printf("errorText:%s\n", errorText);
      return errCode;
  }

      printf("current: %f", current);
      return 0;
  }

  • C++
      #include <stdlib.h>
      #include <stdio.h>
      #include <unistd.h>
      #include <string.h>
      #include <dlfcn.h>
      #include <stdint.h>

      int (*RI_SDK_InitSDK)(int logLevel, char *errorText);

      int (*RI_SDK_CreateModelComponent)(char *group, char *device, char *model, int *descriptor, char *errorText);

      int
      (*RI_SDK_LinkVoltageSensorToController)(int sensorDescriptor, int i2cAdapterDescriptor, uint8_t addr, char *errorText);

      int (*RI_SDK_sensor_VoltageSensor_Current)(int descriptor, float *result, char *errorText);

      int initLibrary() {
      void *handle;
      char *LIB_RISDK = getenv("LIB_RISDK");
      handle = dlopen(strcat(LIB_RISDK, "librisdk.so"), RTLD_NOW);
      if (!handle) {
      /* fail to load the library */
      fprintf(stderr, "Error: %s\n", dlerror());
      return -1;
  }

      *(void **) (&RI_SDK_InitSDK) = dlsym(handle, "RI_SDK_InitSDK");
      *(void **) (&RI_SDK_CreateModelComponent) = dlsym(handle, "RI_SDK_CreateModelComponent");
      *(void **) (&RI_SDK_LinkVoltageSensorToController) = dlsym(handle, "RI_SDK_LinkVoltageSensorToController");
      *(void **) (&RI_SDK_sensor_VoltageSensor_Current) = dlsym(handle, "RI_SDK_sensor_VoltageSensor_Current");
      return 0;
  }

      char errorText[1000]; // текст ошибки. Передается как входной параметр,при возникновении ошибки в эту переменную будет записан текст ошибки
      int sensorDescriptor;
      int i2cDescriptor;
      float current;

      int main() {
      int initErr;
      initErr = initLibrary();
      if (initErr != 0) {
      printf("fail to load init library");
      return initErr;
  }

      int errCode; //код ошибки

      // Инициализация библиотеки RI SDK
      errCode = RI_SDK_InitSDK(3, errorText);
      if (errCode != 0) {
      printf("errorText:%s\n", errorText);
      return errCode;
  }

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

      // Создание компонента датчика тока, напряжения и мощности модели ina219
      char sensor[] = "sensor";
      char voltage_sensor[] = "voltage_sensor";
      char ina219[] = "ina219";
      errCode = RI_SDK_CreateModelComponent(sensor, voltage_sensor, ina219, &sensorDescriptor, errorText);
      if (errCode) {
      printf("errorText:%s\n", errorText);
      return errCode;
  }

      // Связывание i2c с датчиком тока, напряжения и мощности
      errCode = RI_SDK_LinkVoltageSensorToController(sensorDescriptor, i2cDescriptor, 0x41, errorText);
      if (errCode) {
      printf("errorText:%s\n", errorText);
      return errCode;
  }

      // Получение значения силы тока
      errCode = RI_SDK_sensor_VoltageSensor_Current(sensorDescriptor, ¤t, errorText);
      if (errCode) {
      printf("errorText:%s\n", errorText);
      return errCode;
  }

      printf("current: %f", current);
      return 0;
  }

  • Golang
        package main

        /*
        #cgo LDFLAGS: -ldl
        #include <stdlib.h>
        #include <stdio.h>
        #include <unistd.h>
        #include <string.h>
        #include <dlfcn.h>
        #include <stdint.h>

        int (*RI_SDK_InitSDK)(int logLevel, char *errorText);

        int (*RI_SDK_CreateModelComponent)(char *group, char *device, char *model, int *descriptor, char *errorText);

        int
        (*RI_SDK_LinkVoltageSensorToController)(int sensorDescriptor, int i2cAdapterDescriptor, uint8_t addr, char *errorText);

        int (*RI_SDK_sensor_VoltageSensor_Current)(int descriptor, float *result, char *errorText);


        int InitSDK(int logLevel, char *errorText){
        RI_SDK_InitSDK(logLevel,errorText);
    }

        int CreateModelComponent(char *group, char *device, char *model, int *descriptor, char *errorText){
        RI_SDK_CreateModelComponent(group,device,model,descriptor,errorText);
    }

        int LinkVoltageSensorToController(int sensorDescriptor, int i2cAdapterDescriptor, uint8_t addr, char *errorText){
        RI_SDK_LinkVoltageSensorToController(sensorDescriptor,i2cAdapterDescriptor,addr,errorText);
    }

        int sensor_VoltageSensor_Current(int descriptor, float *result, char *errorText){
        RI_SDK_sensor_VoltageSensor_Current(descriptor,result,errorText);
    }

        int initLibrary() {
        void *handle;
        char *LIB_RISDK = getenv("LIB_RISDK");
        handle = dlopen(strcat(LIB_RISDK, "librisdk.so"), RTLD_NOW);
        if (!handle) {
        fprintf(stderr, "Error: %s\n", dlerror());
        return -1;
    }

        *(void **) (&RI_SDK_InitSDK) = dlsym(handle, "RI_SDK_InitSDK");
        *(void **) (&RI_SDK_CreateModelComponent) = dlsym(handle, "RI_SDK_CreateModelComponent");
        *(void **) (&RI_SDK_LinkVoltageSensorToController) = dlsym(handle, "RI_SDK_LinkVoltageSensorToController");
        *(void **) (&RI_SDK_sensor_VoltageSensor_Current) = dlsym(handle, "RI_SDK_sensor_VoltageSensor_Current");
        return 0;
    }
        */
        import "C"
        import "fmt"

        func main() {
        var (
        errorText        [1000]C.char // текст ошибки. Передается как входной параметр,при возникновении ошибки в эту переменную будет записан текст ошибки
        sensorDescriptor C.int
        i2cDescriptor    C.int
        initErr          C.int
        current          C.float
        errCode          C.int
        )

        initErr = C.initLibrary()
        if initErr != 0 {
        fmt.Printf("fail to load init library")
    }

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

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

        // Создание компонента датчика тока, напряжения и мощности модели ina219
        errCode = C.CreateModelComponent(C.CString("sensor"), C.CString("voltage_sensor"), C.CString("ina219"), &sensorDescriptor, &errorText[0])
        if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorText[0]))
        return
    }

        // Связывание i2c с датчиком тока, напряжения и мощности
        errCode = C.LinkVoltageSensorToController(sensorDescriptor, i2cDescriptor, 0x41, &errorText[0])
        if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorText[0]))
        return
    }

        // Получение значения силы тока
        errCode = C.sensor_VoltageSensor_Current(sensorDescriptor, ¤t, &errorText[0])
        if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorText[0]))
        return
    }

        fmt.Printf("current: %f", current)
    }
  • Golang gRPC
      package main

      import (
      "fmt"
      "github.com/rbs-ri/go-risdk"
      )

      func main() {
      //Открываем соединение для работы с API SDK по RPC
      client := risdk.GetClientRPC()
      //Закрываем соединение с RPC
      defer client.Client.Kill()

      // Создание компонента i2c адаптера модели ch341
      i2cDescriptor, errText, errCode, err := client.RoboSdkApi.RI_SDK_CreateModelComponent("connector", "i2c_adapter", "ch341")
      if errText != "" || errCode != 0 || err != nil {
      fmt.Printf("errText: %s; errCode:%d; err: %s", errText, errCode, err)
      return
  }

      // Создание компонента датчика тока, напряжения и мощности модели ina219
      inaSensorDescriptor, errText, errCode, err := client.RoboSdkApi.RI_SDK_CreateModelComponent("sensor", "voltage_sensor", "ina219")
      if errText != "" || errCode != 0 || err != nil {
      fmt.Printf("errText: %s; errCode:%d; err: %s", errText, errCode, err)
      return
  }

      // Связывание i2c с датчиком тока, напряжения и мощности
      errText, errCode, err = client.RoboSdkApi.RI_SDK_LinkVoltageSensorToController(inaSensorDescriptor, i2cDescriptor, 0x41)
      if errText != "" || errCode != 0 || err != nil {
      fmt.Printf("errText: %s; errCode:%d; err: %s", errText, errCode, err)
      return
  }

      // Получение значения силы тока в цепи
      current, errText, errCode, err := client.RoboSdkApi.RI_SDK_Sensor_VoltageSensor_Current(inaSensorDescriptor)
      if errText != "" || errCode != 0 || err != nil {
      fmt.Printf("errText: %s; errCode:%d; err: %s", errText, errCode, err)
      return
  }

      fmt.Printf("current: %v", current)

      return
  }
  • PHP
        <?php
        // Подключаем внешнюю библиотеку для работы с SDK
        $LIB_RISDK_ENV = "LIB_RISDK";
        if (empty(getenv($LIB_RISDK_ENV))) {
        print("Не указана переменная среды LIB_RISDK - выполнение программы невозможно");
        return;
    }

        $libname = '';
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        $libname = '\librisdk.dll';
    } else {
        $libname = "librisdk.so";
    }

        $ffi = FFI::cdef("int RI_SDK_InitSDK(int level,char* errText);
        int RI_SDK_CreateModelComponent(char* group, char* device, char* model, int* descriptor, char* errorTextC);
        int RI_SDK_sensor_VoltageSensor_Current(int desrciptor, float* result, char* errorTextC);
        int RI_SDK_LinkVoltageSensorToController(int sensorDescriptor, int i2cAdapterDescriptor, uint8_t addr, char* errorTextC);"
        , getenv($LIB_RISDK_ENV) . $libname);

        $errorText = $ffi->new('char[1000]', 0); // Выделяем память на строку с ошибкой. Передается как входной параметр,при возникновении ошибки в эту переменную будет записан текст ошибки
        $logLevel = 3; // уровень логирования
        $sensorDescriptor = $ffi->new('int', 0);
        $i2cDescriptor = $ffi->new('int', 0);
        $current = $ffi->new('float', 0);

        // Инициализируем SDK
        $errCode = $ffi->RI_SDK_InitSDK($logLevel, $errorText);
        if ($errCode) {
        print("errorText:" . FFI::string($errorText) . " errCode: " . $errCode . " \n");
        return;
    }

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

        // Создание компонента датчика тока, напряжения и мощности модели ina219
        $errCode = $ffi->RI_SDK_CreateModelComponent("sensor", "voltage_sensor", "ina219", FFI::addr($sensorDescriptor), $errorText);
        if ($errCode) {
        print("errorText:" . FFI::string($errorText) . " errCode: " . $errCode . " \n");
        return;
    }

        // Связывание i2c с датчиком тока, напряжения и мощности
        $errCode = $ffi->RI_SDK_LinkVoltageSensorToController($sensorDescriptor->cdata, $i2cDescriptor->cdata, 0x41, $errorText);
        if ($errCode) {
        print("errorText:" . FFIs::string($errorText) . " errCode: " . $errCode . " \n");
        return;
    }

        // Получение значения силы тока
        $errCode = $ffi->RI_SDK_sensor_VoltageSensor_Current($sensorDescriptor->cdata, FFI::addr($current), $errorText);
        if ($errCode) {
        print("errorText:" . FFI::string($errorText) . " errCode: " . $errCode . " \n");
        return;
    }

        print("current: " . $current);

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

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

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

Навигация

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