forum.boolean.name

forum.boolean.name (http://forum.boolean.name/index.php)
-   Программирование для мобильных устройств (http://forum.boolean.name/forumdisplay.php?f=173)
-   -   Android lib (http://forum.boolean.name/showthread.php?t=18431)

RegIon 04.08.2013 09:21

Android lib
 
Как всем понятно , что Unity, из-за кроссплатформенности не умеет работать с устройствами Android.
Для этого и есть возможность писать библиотеки на java, но не все так гладко.
Вот я нарыл библиотеку для работы с UART преобразователями (https://code.google.com/p/usb-serial...droid-v010.jar) (есть исходник https://code.google.com/p/usb-serial-for-android/)

Я правильно думаю, что просто-так её к юнити не подключить?
А если подключить, то как в C# выполнить подобное:
PHP код:

// Get UsbManager from Android.
UsbManager manager = (UsbManagergetSystemService(Context.USB_SERVICE);

// Find the first available driver.
UsbSerialDriver driver UsbSerialProber.acquire(manager);

if (
driver != null) {
  
driver.open();
  try {
    
driver.setBaudRate(115200);
    
    
byte buffer[] = new byte[16];
    
int numBytesRead driver.read(buffer1000);
    
Log.d(TAG"Read " numBytesRead " bytes.");
  } catch (
IOException e) {
    
// Deal with error.
  
} finally {
    
driver.close();
  } 


Если нельзя, то помогите написать обертку на JAVA, что бы юнити поняла.;)

RegIon 04.08.2013 11:36

Ответ: Android lib
 
Я тут погуглил и понял, что ко всему железу можно обращаться с терминала (к блюпупу тоже) через Busybox (и без него).
Что бы проверть то, как Unity умеет создавать процессы я написал скрипт:
PHP код:

using UnityEngine;
using System;
using System.Collections;
using System.Diagnostics;

public class 
Call MonoBehaviour
{

    
// Use this for initialization
//    private Shell shell;
    
public bool run false;
    public 
string program "";
    public 
string command "";
    public 
string ret "";
    public 
string inp "";
    public 
bool input false;
    public 
bool processing false;
    private 
Process p;
    
//private ProcessStartInfo info;
    
    
void Start ()
    { 
        
        
    }

    
    
// Update is called once per frame
    
void Update ()
    {
        if (
run) {
            if (!
processing) {
                try {
                    
ret "";
                    
= new Process ();
                    
p.StartInfo.RedirectStandardInput true;
                    
p.StartInfo.RedirectStandardOutput true;
                    
//p.StartInfo.RedirectStandardError = true;
                    
p.StartInfo.UseShellExecute false;
                    
p.StartInfo.CreateNoWindow true;
                    
p.StartInfo.FileName program;
                    
p.Start ();
                    
//p.WaitForExit();
                    
processing true;
                    
p.StandardInput.WriteLine (command);
                    
p.StandardInput.Write("\n");
                    
                } catch (
Exception e) {
                    
ret e.Message;
                }
            } else {
                if (!
p.HasExited) {
                    
                    
ret += p.StandardOutput.ReadToEnd ();// + p.StandardError.ReadToEnd();
                
} else {
                    
run false;
                    
processing false;
                }
            }
        }
    }
    
    
void OnGUI ()
    {
        
        if (
GUI.Button (new Rect (1010Screen.width 2032), "Press for run")) {
            
run true;    
        }
        
program GUI.TextArea (new Rect (1042 8Screen.width 2032), program);
        
command GUI.TextArea (new Rect (Screen.width 1042 8Screen.width 2032), command);
        
        
        
        
GUI.TextField (new Rect (1090Screen.width 20Screen.height 90), ret);
    }


(вешаем на камеру )

Имхо кастыль, но работает (Huawei ascend), может у кого нет.

UPD. SU не смог вызвать - повис.
UPD. не могу вызвать утилиты busybox, сам он вызывается, но microcom - не выдает ничего, может че с stdout.

Короче, почему-то нельзя выполнить функции с параметрами, например не могу вызвать cmd help.
делал по подобию http://stackoverflow.com/questions/6...ide-su-process

Помогите
!

pax 05.08.2013 11:01

Ответ: Android lib
 
Давно писал обращение к вибратору (не знаю, поможет или нет):
PHP код:

using System;
using UnityEngine;
public class 
Vibrator IDisposable
{
    private 
AndroidJavaObject vibratorObject;

    private 
Vibrator()
    {
        
using (AndroidJavaClass androidJavaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            
using (AndroidJavaObject activity androidJavaClass.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                
vibratorObject activity.Call<AndroidJavaObject>("getSystemService", new object[] {"vibrator"});
            }
        }
    }

    public 
void VibratePattern(long[] patternint repeat_index)
    {
        
vibratorObject.Call("vibratePattern", new object[]
        {
            
pattern
            
repeat_index
        
});
    }
    public 
void Vibrate(long milliseconds)
    {
        
vibratorObject.Call("vibrate", new object[]
        {
            
milliseconds
        
});
    }

    public 
void Cancel()
    {
        
vibratorObject.Call("cancel", new object[0]);
    }

    public 
void Dispose()
    {
        
vibratorObject.Dispose();
    }


    public static 
readonly Vibrator Instance = new Vibrator();



RegIon 08.08.2013 14:40

Ответ: Android lib
 
PAX, а как им пользоваться? Имхо закинуть в Plugins и :
Цитата:

private Vibrator v = new Vibrator();
Не работает(.

pax 08.08.2013 14:42

Ответ: Android lib
 
Vibrator.Instance.Vibrate(100);
И включить в манифесте разрешения на управление вибратором. На сколько я помню так:
Код:

<uses-permission android:name="android.permission.VIBRATE" />

RegIon 08.08.2013 15:35

Ответ: Android lib
 
Что-то я не нашел разрешение для USB.
http://developer.android.com/reference/android/hardware/usb/UsbManager.html

pax 08.08.2013 15:45

Ответ: Android lib
 
Беглый поиск вывел вот на такой ресрус https://code.google.com/p/usb-serial-for-android/
Возможно поможет...

RegIon 08.08.2013 15:48

Ответ: Android lib
 
Цитата:

Сообщение от pax (Сообщение 264995)
Беглый поиск вывел вот на такой ресрус https://code.google.com/p/usb-serial-for-android/
Возможно поможет...

В первом посту .

pax 08.08.2013 15:51

Ответ: Android lib
 
Ну больше помочь ничем не могу :pardon:

RegIon 08.08.2013 16:33

Ответ: Android lib
 
http://answers.unity3d.com/questions...using-jni.html

Настрочил вызовы jni:
PHP код:

using UnityEngine;
using System;
using System.Runtime.InteropServices;

public class 
USB_Serial IDisposable {
    
    private 
AndroidJavaObject usb;
    private 
AndroidJavaObject dr;
    
    private 
AndroidJavaClass driver = new AndroidJavaClass("com.hoho.android.usbserial.driver.UsbSerialDriver");
    private 
AndroidJavaClass prober = new AndroidJavaClass("com.hoho.android.usbserial.driver.UsbSerialProber");
    
        
    private 
USB_Serial(){
        
using(AndroidJavaClass ajc = new AndroidJavaClass("com.unity3d.player.UnityPlayer")){
            
using(AndroidJavaObject activity ajc.GetStatic<AndroidJavaObject>("currentActivity")){
                
usb activity.Call<AndroidJavaClass>("getSystemService",new object[] {"usb"});
                
dr prober.Call<AndroidJavaClass>("acquire",new object[]{usb}); 
            }
        }
    }
    
    private 
bool dropen false;
    public 
void Open(int speed,int dataBits,int flow,int parity){
        if(
dr!=null){
            
dr.Call("open",new object[0]);
        try{    
            
dr.Call("setParameters",new object[]{speed,dataBits,flow,parity});
            
dropen=true;
            }
            catch{
                
            }
        }    
    }
    
    public 
int Read(){
        
int read_c = -1;
        if(
dropen){
            
        }
        return 
read_c;
    }
    
    public 
void Dispose()
    {
        
usb.Dispose();
        
dr.Dispose();
    }
    
    public static 
readonly USB_Serial Port = new USB_Serial();


Сей возникла проблем с:
PHP код:

/**
     * Reads as many bytes as possible into the destination buffer.
     *
     * @param dest the destination byte buffer
     * @param timeoutMillis the timeout for reading
     * @return the actual number of bytes read
     * @throws IOException if an error occurred during reading
     */
    
public int read(final byte[] dest, final int timeoutMillisthrows IOException;

    
/**
     * Writes as many bytes as possible from the source buffer.
     *
     * @param src the source byte buffer
     * @param timeoutMillis the timeout for writing
     * @return the actual number of bytes written
     * @throws IOException if an error occurred during writing
     */
    
public int write(final byte[] src, final int timeoutMillisthrows IOException;

    
/**
     * Sets various serial port parameters.
     *
     * @param baudRate baud rate as an integer, for example {@code 115200}.
     * @param dataBits one of {@link #DATABITS_5}, {@link #DATABITS_6},
     *            {@link #DATABITS_7}, or {@link #DATABITS_8}.
     * @param stopBits one of {@link #STOPBITS_1}, {@link #STOPBITS_1_5}, or
     *            {@link #STOPBITS_2}.
     * @param parity one of {@link #PARITY_NONE}, {@link #PARITY_ODD},
     *            {@link #PARITY_EVEN}, {@link #PARITY_MARK}, or
     *            {@link #PARITY_SPACE}.
     * @throws IOException on error setting the port parameters
     */
    
public void setParameters(
            
int baudRateint dataBitsint stopBitsint paritythrows IOException

А именно с read, так как наверно прямо сделать так:
PHP код:

public int read(ref byte[] dataint ms) {
    var 
len dr.Call<int>("read",new object[]{data,ms});
return 
len;


НЕЛЬЗЯ.?

Так как тогда?
Сам класс тут.


UPD:
Вечно показывает подключенное устройство.
Не отправляет и не принимает .

pax 08.08.2013 19:42

Ответ: Android lib
 
А это пробовал?

http://docs.unity3d.com/Documentatio...ByteArray.html

http://docs.unity3d.com/Documentatio...ayElement.html


Часовой пояс GMT +4, время: 01:21.

vBulletin® Version 3.6.5.
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Перевод: zCarot