2015年3月22日 星期日

Android Bluetooth Le Gatt Testing

Ref:
1. Android Studio example Bluetooth Le Gatt
2. Hardware:
    ASUS X450J (Windows 10 Preview, Android Studio 1.0)
    ASUS Zenfone 6
Test procedure
1. Import sample

2. Check the main_activity

3. Run the example

4. Show the results on Zenfone 6.



2015年3月1日 星期日

Lego C#

Ref: http://legoev3.codeplex.com/documentation#References
1. Hardware:
    ASUS X450J (Windows 10 Preview)
    Lego EV3 (PortA : Left wheel, PortB: Right wheel

2. MainWindow.xaml
<Window x:Class="WPFLego1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Closing="Window_Closing">
    <Grid Margin="0,0,340,237">
        <Button Name="前進" MouseEnter="前進_MouseEnter" MouseLeave="前進_MouseLeave" Content="前進" Margin="172,10,-172,-10" />
        <Button x:Name="後退" MouseEnter="後退_MouseEnter" MouseLeave="後退_MouseLeave" Content="後退" Margin="172,158,-172,-158" />
        <Button x:Name="左轉" MouseEnter="左轉_MouseEnter" MouseLeave="左轉_MouseLeave" Content="左轉" Margin="-10,85,10,-85" />
        <Button x:Name="右轉" MouseEnter="右轉_MouseEnter" MouseLeave="右轉_MouseLeave" Content="右轉" Margin="354,85,-354,-85" />
    </Grid>
</Window>

3. MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Lego.Ev3.Core;
using Lego.Ev3.Desktop;
using System.Threading.Tasks;

namespace WPFLego1
{
    /// <summary>
    /// MainWindow.xaml 的互動邏輯
    /// </summary>
   
   
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            // Settings
            EV3B = new Brick(new BluetoothCommunication("COM7"));
            EV3B.BrickChanged += EV3B_BrickChanged;
            EV3B.ConnectAsync();
        }

        void EV3B_BrickChanged(object sender, BrickChangedEventArgs e)
        {
            for (int i = 0; i < e.Ports.Count; i++)
            {
                //this.Title += e.Ports[InputPort.A].SIValue.ToString();
            }
        }

        Brick EV3B;
        private void 前進_MouseEnter(object sender, MouseEventArgs e)
        {
            this.Title = "前進";
            EV3B.DirectCommand.TurnMotorAtPowerAsync(OutputPort.All, 50);

        }

        private void 前進_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Title = "停止前進";
            EV3B.DirectCommand.TurnMotorAtPowerAsync(OutputPort.All, 0);
        }

        private void 後退_MouseEnter(object sender, MouseEventArgs e)
        {
            this.Title = "後退";
            EV3B.DirectCommand.TurnMotorAtPowerAsync(OutputPort.All, -50);

        }

        private void 後退_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Title = "停止後退";
            EV3B.DirectCommand.TurnMotorAtPowerAsync(OutputPort.All, 0);
        }

        private void 左轉_MouseEnter(object sender, MouseEventArgs e)
        {
            this.Title = "左轉";
            EV3B.DirectCommand.TurnMotorAtPowerAsync(OutputPort.A, 50);
            EV3B.DirectCommand.TurnMotorAtPowerAsync(OutputPort.B, -50);

        }

        private void 左轉_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Title = "停止左轉";
            EV3B.DirectCommand.TurnMotorAtPowerAsync(OutputPort.All, 0);
        }
        private void 右轉_MouseEnter(object sender, MouseEventArgs e)
        {
            this.Title = "右轉";
            EV3B.DirectCommand.TurnMotorAtPowerAsync(OutputPort.A, -50);
            EV3B.DirectCommand.TurnMotorAtPowerAsync(OutputPort.B, 50);

        }

        private void 右轉_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Title = "停止右轉";
            EV3B.DirectCommand.TurnMotorAtPowerAsync(OutputPort.All, 0);
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            EV3B.DirectCommand.StopMotorAsync(OutputPort.All, true);
            EV3B.Disconnect();

        }
    }
}

2015年2月18日 星期三

Python play a video file

Ref:http://www.thecodingforums.com/threads/python-help-sending-a-play-command-to-quicktime-or-playing-amovie-in-python.702701/

1.
import subprocess
subprocess.Popen(["open", "path/to/the/movie.file"])

2. Quicktimeplayer can not auto play
refhttp://www.defaults-write.com/quicktime-player-x-enable-auto-play-feature/#.VOWJ6bCUf6Y

defaults write com.apple.QuickTimePlayerX MGPlayMovieOnOpen 1

Disable autoplay

defaults write com.apple.QuickTimePlayerX MGPlayMovieOnOpen 0


Android tcp client (Send data from client and get server response) - II

This example show the interactive action between server and client.
1. tcpserver : Add print c.recv(1024) before send response in server side as follows
#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   print c.recv(1024)
   c.send('Thank you for connecting')
   c.close()                # Close the connection  

2. tcpclient: Add send data before get response from server side.
Socket socket = null;

            try {
                socket = new Socket(dstAddress, dstPort);

                ByteArrayOutputStream byteArrayOutputStream =
                        new ByteArrayOutputStream(1024);
                byte[] buffer = new byte[1024];

                int bytesRead;
                DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
                DOS.writeUTF("手機送出訊息");
                InputStream inputStream = socket.getInputStream();

    /*
     * notice:
     * inputStream.read() will block if no data return
     */
                while ((bytesRead = inputStream.read(buffer)) != -1){
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                    response += byteArrayOutputStream.toString("UTF-8");
                }

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                response = "UnknownHostException: " + e.toString();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                response = "IOException: " + e.toString();
            }finally{
                if(socket != null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

Android tcp client

Ref:http://android-er.blogspot.tw/2014/02/android-sercerclient-example-client.html
1. Macbook pro/Android Studio
2. Server :
   http://csjoublog.blogspot.tw/2015/02/python-test-for-sever-and-client.html
3. Android client building procedure
3-1 Create a new project
3-2 Copy xml block and paste into the RealativeLayout tag of activivty_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:orientation="vertical"
        tools:context=".MainActivity" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:autoLink="web"
            android:text="http://android-er.blogspot.com/"
            android:textStyle="bold" />
        <EditText
            android:id="@+id/address"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="dstAddress" />
        <EditText
            android:id="@+id/port"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="dstPort" />
        <Button
            android:id="@+id/connect"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Connect..."/>
        <Button
            android:id="@+id/clear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Clear"/>
        <TextView
            android:id="@+id/response"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </LinearLayout>

</RelativeLayout>
3-3 Copy java code into Mainactivity.java
package com.example.csjou.androidclient2;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView textResponse;
    EditText editTextAddress, editTextPort;
    Button buttonConnect, buttonClear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextAddress = (EditText)findViewById(R.id.address);
        editTextPort = (EditText)findViewById(R.id.port);
        buttonConnect = (Button)findViewById(R.id.connect);
        buttonClear = (Button)findViewById(R.id.clear);
        textResponse = (TextView)findViewById(R.id.response);

        buttonConnect.setOnClickListener(buttonConnectOnClickListener);

        buttonClear.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                textResponse.setText("");
            }});
    }

    OnClickListener buttonConnectOnClickListener =
            new OnClickListener(){

                @Override
                public void onClick(View arg0) {
                    MyClientTask myClientTask = new MyClientTask(
                            editTextAddress.getText().toString(),
                            Integer.parseInt(editTextPort.getText().toString()));
                    myClientTask.execute();
                }};

    public class MyClientTask extends AsyncTask<Void, Void, Void> {

        String dstAddress;
        int dstPort;
        String response = "";

        MyClientTask(String addr, int port){
            dstAddress = addr;
            dstPort = port;
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            Socket socket = null;

            try {
                socket = new Socket(dstAddress, dstPort);

                ByteArrayOutputStream byteArrayOutputStream =
                        new ByteArrayOutputStream(1024);
                byte[] buffer = new byte[1024];

                int bytesRead;
                InputStream inputStream = socket.getInputStream();

    /*
     * notice:
     * inputStream.read() will block if no data return
     */
                while ((bytesRead = inputStream.read(buffer)) != -1){
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                    response += byteArrayOutputStream.toString("UTF-8");
                }

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                response = "UnknownHostException: " + e.toString();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                response = "IOException: " + e.toString();
            }finally{
                if(socket != null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            textResponse.setText(response);
            super.onPostExecute(result);
        }

    }

}
3-4 Add internet permission into AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.csjou.androidclient2" >
<uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
4. Run server
5. Run emulator OK.

6. Run Zenfone 6 OK.

2015年2月16日 星期一

Python test for sever and client

Ref:http://www.tutorialspoint.com/python/python_networking.htm

1. Macbook Pro (2014 mid, iOS 10.9.5)
2. Edit: Sublime
3. server.py
#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection
4. Client.py
#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done
Test 2:
ASUS X450J (Windows 10 Preview)
Python26
2-1. Server:
#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   print c.recv(1024)
   c.send('Thank you for connecting')
   c.close()                # Close the connection   
2-2 Client:
#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
s.send('Hello Server.')
print s.recv(1024)
s.close                     # Close the socket when done




Mac 檢視 Android Studio SDK Sample code

Ref : https://helpx.adobe.com/x-productkb/global/access-hidden-user-library-files.html
1 In the Finder, choose Go > Go To Folder.
2. In the Go To Folder dialog, type ~/Library

3. Click Go
4. Change to Android/SDK/Samples