災害地画像送信アプリケーション
プログラム
備考
今見るとかなり鈍くさいコードになってる.
サーバサイド(Java アプリケーション)
LiveCamServer
public class LiveCamServer { public static void main(String[] args) { int port = 36574; LiveCamServer server = new LiveCamServer(); if (args.length == 1) { port = Integer.parseInt(args[0]); } else { System.err.println("args err!!"); System.exit(-1); } server.start(port); } public void start(int port) { ServerSocket server; Socket socket; LiveCamServerThread serverThread; try { server = new ServerSocket(port); System.err.println("LiveCam Server Start:" + port); while(true) { try { socket = server.accept(); serverThread = new LiveCamServerThread(socket); serverThread.start(); } catch (IOException e) { System.err.println(e); } } } catch (IOException e) { System.err.println(e); } } }
LiveCamServerThread
public class LiveCamServerThread extends Thread { private static List<LiveCamServerThread> serverThreads = new ArrayList<LiveCamServerThread>(); private Socket socket; private String currentDir; public LiveCamServerThread(Socket socket) { super(); File currentDirectory = new File("."); currentDir = currentDirectory.getAbsoluteFile().getParent(); this.socket = socket; serverThreads.add(this); } public void run() { ObjectInputStream ois = null; BufferedInputStream bis = null; FileOutputStream fos = null; ArrayList<ArrayList> deviceInfoList = null; String filepath = ""; String deviceid = ""; byte[] buf = new byte[1024]; try { ois = new ObjectInputStream(socket.getInputStream()); deviceInfoList = (ArrayList<ArrayList>)ois.readObject(); //deviceInfoToString(deviceInfoList); deviceid = (String) deviceInfoList.get(0).get(10); //deviceid = "test"; filepath = createPath(deviceid); } catch(Exception e) { e.printStackTrace(); } try { bis = new BufferedInputStream(socket.getInputStream()); fos = new FileOutputStream(filepath); int len = 0; while((len = bis.read(buf, 0, 1024)) != -1) { fos.write(buf,0,len); } deviceInfoToString(deviceInfoList, filepath); fos.close(); socket.close(); serverThreads.remove(this); } catch (IOException e) { System.err.println(e); } } // create file path private String createPath(String dirName) { String filepath; File imgdir = new File(currentDir, dirName); if (!imgdir.exists()) imgdir.mkdir(); Calendar now = Calendar.getInstance(); int y = now.get(Calendar.YEAR); int mo = now.get(Calendar.MONTH) + 1; int d = now.get(Calendar.DATE); int h = now.get(now.HOUR_OF_DAY); int m = now.get(now.MINUTE); int s = now.get(now.SECOND); filepath = imgdir.getAbsolutePath() + "/" + "_" + y + "_" + mo + "_" + d + "_" + h + "_" + m + "_" + s + ".jpg"; return filepath; } //toString Device Info private void deviceInfoToString(ArrayList<ArrayList> list, String filepath) { try{ File file = new File("log.txt"); FileOutputStream fos = new FileOutputStream(file, true); OutputStreamWriter osw = new OutputStreamWriter(fos); PrintWriter pw = new PrintWriter(osw); for (int i = 0; i < list.get(0).size(); i++) { if (i < list.get(0).size()-1) { System.out.print(list.get(0).get(i) + ","); pw.print(list.get(0).get(i) + ","); } else { System.out.println(list.get(0).get(i)); pw.println(list.get(0).get(i)); } } for (int i = 0; i < list.get(1).size(); i++) { System.out.println(list.get(1).get(i)); pw.println(list.get(1).get(i)); } System.out.println("" + filepath); pw.printhttp://blog.hatena.ne.jp/majiro35/majimem.hatenablog.com/edit?editinplace=1#previewln("Repository:" + filepath); pw.println("-"); System.out.println("-"); pw.close(); }catch(IOException e){ System.out.println(e); } } }
クライアントサイド(Android アプリケーション)
LiveCamClient
public class LiveCamClient extends Activity { // target server (default value) private final static String IP = "10.70.243.170"; private final static String PORT = "36574"; private final static String DIR_NAME = "LiveCam"; private final static String TMP_PIC_NAME = "tmp.jpg"; private final static int TAKE_PIC_START = 2; private final static int MODE_CAMERA = 0; private final static int MODE_MOVIE = 1; private Socket socket; private OutputStream os; private SurfaceView cameraView = null; private Camera camera = null; private String pictureFilePath = null; public Handler sendhandler = new Handler(); public Handler timerhandler = new Handler(); public Timer startTimer = new Timer(); public Timer stopTimer = new Timer(); public WifiManager manager = null; private String ip = IP; private String port = PORT; private int tpi = 0; //take picture interval private int pot = 0; //period of time private int mode = MODE_CAMERA; //default mode private Button btnstart; private Spinner spinter; private Spinner sppot; private EditText editip; private EditText editport; private CheckBox checkmode; private boolean connectErr = true; private boolean sendErr = false; private boolean pushStart = false; @Override protected void onCreate(Bundle savedInstanceState) { android.util.Log.v("lifeCycle", "onCreate(Bundle savedInstanceState)"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_real_time_view); btnstart = (Button)findViewById(R.id.button1); btnstart.setTextSize(27); spinter = (Spinner)findViewById(R.id.spinner1); spinter.setEnabled(false);; sppot = (Spinner)findViewById(R.id.spinner2); sppot.setEnabled(false); editip = (EditText)findViewById(R.id.editText1); editip.setGravity(Gravity.RIGHT); editip.setText(ip, BufferType.NORMAL); editport = (EditText)findViewById(R.id.editText2); editport.setGravity(Gravity.RIGHT); editport.setText(port, BufferType.NORMAL); checkmode = (CheckBox)findViewById(R.id.checkBox1); File dir = new File(Environment.getExternalStorageDirectory(), DIR_NAME); if (!dir.exists()) dir.mkdir(); File file = new File(dir, TMP_PIC_NAME); pictureFilePath = file.getAbsolutePath(); //wifi scan manager = (WifiManager) getSystemService(WIFI_SERVICE); if (manager.isWifiEnabled() == false) manager.setWifiEnabled(true); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //btnstart event btnstart.setOnClickListener(new OnClickListener() { public void onClick(View v) { android.util.Log.v("conf", "btncam push"); SpannableStringBuilder sb = (SpannableStringBuilder)editip.getText(); ip = sb.toString(); sb = (SpannableStringBuilder)editport.getText(); port = sb.toString(); if (port.length() == 0) port = "0"; pushStart = true; setupCameraView(); } }); checkmode.setOnClickListener(new OnClickListener() { public void onClick(View v) { android.util.Log.v("conf", "check push"); if (checkmode.isChecked()) { mode = MODE_MOVIE; spinter.setEnabled(true); sppot.setEnabled(true); } else { mode = MODE_CAMERA; spinter.setEnabled(false); sppot.setEnabled(false); } } }); //spiner event spinter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView parent,View view, int position,long id) { switch (position) { case 0: tpi = 3000; break; case 1: tpi = 5000; break; case 2: tpi = 10000; break; case 3: tpi = 15000; break; case 4: tpi = 30000; break; case 5: tpi = 60000; break; default: android.util.Log.v("conf", "tpi non"); } android.util.Log.v("conf", "tpi " + tpi); } public void onNothingSelected(AdapterView parent) { //code } }); //sppot event sppot.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView parent,View view, int position,long id) { switch (position) { case 0: pot = 10000; break; case 1: pot = 15000; break; case 2: pot = 30000; break; case 3: pot = 60000; break; case 4: pot = 90000; break; case 5: pot = 120000; break; case 6: pot = 180000; break; case 7: pot = 300000; break; case 8: pot = 600000; break; case 9: pot = 1800000; break; case 10: pot = 3600000; break; default: android.util.Log.v("conf", "pot non"); } android.util.Log.v("conf", "pot " + pot); } public void onNothingSelected(AdapterView parent) { //code } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { android.util.Log.v("method", "onCreateOptionsMenu(Menu menu)"); getMenuInflater().inflate(R.menu.real_time_view, menu); return true; } @Override protected void onStop() { android.util.Log.v("lifeCycle", "onStop()"); super.onStop(); disConnect(); } @Override public boolean onKeyDown(int keyCode, KeyEvent e) { android.util.Log.v("method", "onKeyDown(int keyCode, KeyEvent e)"); if (keyCode == KeyEvent.KEYCODE_BACK) { new AlertDialog.Builder(this) .setTitle("Confirmation") .setMessage("Continue?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //code } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { disConnect(); finish(); } }) .show(); return true; } else { return false; } } @Override public boolean onTouchEvent(MotionEvent e) { android.util.Log.v("method", "onTouchEvent(MotionEvent e)"); int action = e.getAction() & MotionEvent.ACTION_MASK; if (action == MotionEvent.ACTION_DOWN) { android.util.Log.v("onTouchEvent", "action down"); if (pushStart) { wrapConnect(ip, Integer.parseInt(port)); waitConnect(); if (socket != null) { Log.v("conf", "socket != null"); if (mode == MODE_CAMERA) { callTakePicture(); } else if (mode == MODE_MOVIE) { tpiTimer(TAKE_PIC_START, tpi); potTimer(pot); } } else { Log.v("conf", "socket == null"); } } else { Log.v("conf", "pushStart == false"); } } else if (action == MotionEvent.ACTION_POINTER_UP) { android.util.Log.v("onTouchEvent", "action up"); } else if (action == MotionEvent.ACTION_HOVER_MOVE) { android.util.Log.v("onTouchEvent", "action move" + e.getX() + "," + e.getY()); } return true; } public void callConnectErrDialog() { android.util.Log.v("method", "callConnectErrDialog()"); new AlertDialog.Builder(this) .setTitle("Connection Error!") .setMessage("To exit") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //code finish(); } }) .show(); } public void wrapConnect(final String ip, final int port) { android.util.Log.v("method", "rapConnect()"); new Thread() { public void run() { try { Log.v("conf", "connect start"); connect(ip, port); } catch (Exception e) { disConnect(); Log.v("err", "connect()"); } } }.start(); } private void connect(String ip,int port) { Log.v("method", "connect(String ip,int port)"); ObjectOutputStream oos = null; ArrayList<ArrayList> deviceInfoList = null; try { Log.v("conf", "connecting" + ip + " " + port); socket = new Socket(ip,port); connectErr = false; os = socket.getOutputStream(); oos = new ObjectOutputStream(socket.getOutputStream()); Log.v("conf", "connect end"); } catch (Exception e) { Log.v("err", "connect err"); connectErr = true; disConnect(); } try { if (!connectErr) { deviceInfoList = getDeviceInfoList(); oos.writeObject(deviceInfoList); oos.flush(); Log.v("conf", "send " + deviceInfoList.get(8)); } } catch(Exception e) { android.util.Log.v("err", "oos.write"); } } private void disConnect() { android.util.Log.v("method", "disconnect()"); try { socket.close(); } catch (Exception e) { android.util.Log.v("err", "socket.close()"); } finally { socket = null; } } private void setupCameraView() { android.util.Log.v("method", "setupCameraView()"); cameraView = new SurfaceView(this); SurfaceHolder holder = cameraView.getHolder(); holder.addCallback(new SurfaceHolder.Callback(){ public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { try { WindowManager manager = (WindowManager)getSystemService(WINDOW_SERVICE); int r = manager.getDefaultDisplay().getRotation(); int d = 0; switch(r){ case Surface.ROTATION_0: d = 90; break; case Surface.ROTATION_90: d = 0; break; case Surface.ROTATION_180: d = 270; break; case Surface.ROTATION_270: d = 180; break; } camera.setDisplayOrientation(d); camera.startPreview(); } catch(Exception e){ e.printStackTrace(); } } public void surfaceCreated(SurfaceHolder holder) { try { camera = Camera.open(); camera.setPreviewDisplay(holder); } catch(Exception e){ e.printStackTrace(); } } public void surfaceDestroyed(SurfaceHolder holder) { camera.setPreviewCallback(null); camera.stopPreview(); camera.release(); camera = null; } }); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); setContentView(cameraView); } private void callTakePicture() { android.util.Log.v("method", "callTakePicture()"); try { camera.takePicture(null, null, new Camera.PictureCallback(){ public void onPictureTaken(byte[] data, Camera camera) { try { camera.startPreview(); FileOutputStream fos = new FileOutputStream(pictureFilePath); fos.write(data); fos.close(); sendImg(data); } catch(Exception e){ android.util.Log.v("method", "save pic cath e"); } } }); } catch(Exception e){ e.printStackTrace(); } } public void sendImg(final byte[] imgBuf) { android.util.Log.v("method", "sendImg()"); new Thread(new Runnable() { public void run() { sendErr = false; try { if (socket != null && socket.isConnected()) { android.util.Log.v("conf", pictureFilePath); os.write(imgBuf); os.flush(); os.close(); } } catch (Exception e) { sendErr = true; } //handler sendhandler.post(new Runnable() { public void run() { if (!sendErr) android.util.Log.v("conf", "send success"); else android.util.Log.v("err", "send fail"); } }); } }).start(); } private void tpiTimer(int startTime, int interval) { startTimer.schedule(new TimerTask() { @Override public void run() { timerhandler.post(new Runnable() { public void run() { wrapConnect(ip, Integer.parseInt(port)); waitConnect(); if (socket != null) { Log.v("conf", "socket != null"); callTakePicture(); } else { Log.v("conf", "socket == null"); } } }); } }, startTime, interval); // 開始からstartTime後に実行,interval間隔で実行 } private void potTimer(int pot) { stopTimer.schedule(new TimerTask() { @Override public void run() { timerhandler.post(new Runnable() { public void run() { startTimer.cancel(); disConnect(); finish(); } }); } }, pot); // 開始からpot後に実行 } private void waitConnect() { try { Thread.sleep(100); if (connectErr) { disConnect(); callConnectErrDialog(); } else { connectErr = true; } } catch (Exception e) { android.util.Log.v("err", "connectStop()"); } } private ArrayList<ArrayList> getDeviceInfoList() { ArrayList<String> deviceInfoList = new ArrayList<String>(); Integer n; //list num 0 to 10 String ip = "IP null"; String mac = "MAC null"; String ssid = "SSID null"; String bssid = "BSSID null"; String networkid = "Network ID null"; String linkSpead = "Link Spead null"; String iccid = "ICCID null"; String subscriberid = "Subscriber ID null"; String deviceid = "Device ID null"; String osVersion = "OS Version null"; String productName = "Product Name null"; if (manager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) { android.util.Log.v("conf", "call startScan()"); manager.startScan(); } //get connect wifi info WifiInfo wInfo = manager.getConnectionInfo(); n = wInfo.getIpAddress(); ip = ((n >> 0) & 0xFF) + "." + ((n >> 8) & 0xFF) + "." + ((n >> 16) & 0xFF) + "." + ((n >> 24) & 0xFF); mac = wInfo.getMacAddress(); ssid = wInfo.getSSID(); bssid = wInfo.getBSSID(); n = wInfo.getNetworkId(); networkid = n.toString(); n = wInfo.getLinkSpeed(); linkSpead = n.toString(); //get device info TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); iccid = telephonyManager.getSimSerialNumber(); subscriberid = telephonyManager.getSubscriberId(); deviceid = telephonyManager.getSimSerialNumber(); osVersion = Build.VERSION.RELEASE; productName = Build.PRODUCT; //add list deviceInfoList.add(ip); deviceInfoList.add(mac); deviceInfoList.add(ssid); deviceInfoList.add(bssid); deviceInfoList.add(networkid); deviceInfoList.add(linkSpead); deviceInfoList.add(iccid); deviceInfoList.add(subscriberid); deviceInfoList.add(deviceid); deviceInfoList.add(osVersion); deviceInfoList.add(productName); List<ScanResult> wifiList = manager.getScanResults(); ArrayList<String> wifiInfoList = new ArrayList<String>(); for (int i = 0; i < wifiList.size(); ++i) { wifiInfoList.add(wifiList.get(i).SSID + "," + wifiList.get(i).BSSID + "," + wifiList.get(i).level); } ArrayList<ArrayList> result = new ArrayList<ArrayList>(); result.add(deviceInfoList); result.add(wifiInfoList); return result; } }