יום שני, 3 ביוני 2013

Getting USB device Interfaces

 

The following code is part of the MissileLauncherActivity of the MissileLauncher api Demo.
The onResume method
The onResume method may be called due to intend invocation caused by the USB device plugin or disconnecting.
The method retrieve the UsbDevice object from the calling intend data. the USBDevice Repents a connected USB device and contains methods to access its identifying information, interfaces, and endpoints. .

  1:     @Override
  2:     public void onResume() {
  3:         super.onResume();
  4:         mSensorManager.registerListener(mGravityListener, mGravitySensor,
  5:                 SensorManager.SENSOR_DELAY_NORMAL);
  6: 
  7:         Intent intent = getIntent();
  8:         Log.d(TAG, "intent: " + intent);
  9:         String action = intent.getAction();
 10: 
 11:         UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
 12:         if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
 13:             setDevice(device);
 14:         } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
 15:             if (mDevice != null && mDevice.equals(device)) {
 16:                 setDevice(null);
 17:             }
 18:         }
 19:     }

The setDevice method
The setDevice method tries to pitch the USB interface out of the usbdevice and tries to fetch the USB interface type interrupt  out of this endpoint.
The method tries to open connection to the device using the UsbManager.

  1:  private void setDevice(UsbDevice device) {
  2:         Log.d(TAG, "setDevice " + device);
  3:         if (device.getInterfaceCount() != 1) {
  4:             Log.e(TAG, "could not find interface");
  5:             return;
  6:         }
  7:         UsbInterface intf = device.getInterface(0);
  8:         // device should have one endpoint
  9:         if (intf.getEndpointCount() != 1) {
 10:             Log.e(TAG, "could not find endpoint");
 11:             return;
 12:         }
 13:         // endpoint should be of type interrupt
 14:         UsbEndpoint ep = intf.getEndpoint(0);
 15:         if (ep.getType() != UsbConstants.USB_ENDPOINT_XFER_INT) {
 16:             Log.e(TAG, "endpoint is not interrupt type");
 17:             return;
 18:         }
 19:         mDevice = device;
 20:         mEndpointIntr = ep;
 21:         if (device != null) {
 22:             UsbDeviceConnection connection = mUsbManager.openDevice(device);
 23:             if (connection != null && connection.claimInterface(intf, true)) {
 24:                 Log.d(TAG, "open SUCCESS");
 25:                 mConnection = connection;
 26:                 Thread thread = new Thread(this);
 27:                 thread.start();
 28: 
 29:             } else {
 30:                 Log.d(TAG, "open FAIL");
 31:                 mConnection = null;
 32:             }
 33:          }
 34:     }

Sources
http://developer.android.com/guide/topics/connectivity/usb/host.html

יום ראשון, 2 ביוני 2013

Php frameworks lead post

I found the following post very interesting.
The Post compare between 4 most popular PHP frameworks.
yiiframework
CodeIgniter
Zend Framework
CakePHP

Custom button in gtk

A simple GTK program that demonstrate the constructing of custom button.

  1: require 'gtk'
  2: require 'gdk_pixbuf'
  3: 
  4: #Returns image from image file 
  5: def load_image_from_file(file_path)
  6:     
  7:   pixbuf = Gdk::Pixbuf.new file_path
  8:     
  9:   pixmap, mask = pixbuf.render_pixmap_and_mask
 10:     
 11:   image  = Gtk::Pixmap.new(pixmap, mask)
 12: end
 13: 
 14: window = Gtk::Window.new Gtk::WINDOW_TOPLEVEL
 15: 
 16: window.signal_connect('delete_event') { Gtk.main_quit }
 17: 
 18: window.border_width 20
 19: 
 20: window.set_title "Custom button"
 21: 
 22: button = Gtk::Button.new
 23: 
 24: vbox = Gtk::VBox.new
 25: 
 26: button.add vbox
 27: 
 28: label = Gtk::Label.new "Press the Lion bellow"
 29: 
 30: vbox.pack_start label
 31: 
 32: image = load_image "Lion.png"
 33: 
 34: vbox.pack_start image
 35: 
 36: window.add button
 37: 
 38: window.show_all
 39: 
 40: Gtk.main

Sources:
http://ruby-gnome.sourceforge.net/tutorial/c429.html
http://zetcode.com/tutorials/gtktutorial/gtkevents/

ActiveMQ simple listener

I wrote a simple listener to the publisher from previous ActiveMQ post: activemq-topic-sender

The MessageListener callback class that’s receives notification when a topic message has received.

  1: private class TextMessageListener implements MessageListener {
  2:  public void onMessage(Message message) {
  3:   try {
  4:         System.out.println("Got the Message  TimeStamp: "
  5:             +  message.getJMSTimestamp());
  6:         System.out.println("Got the Message JMS ID : "
  7:             +  message.getJMSMessageID() );
  8:         
  9:         TextMessage theMsg = (TextMessage)message;
 10:         System.out.println("The message:" + theMsg.getText());
 11:   
 12:   } catch (JMSException e) {
 13:    e.printStackTrace();
 14:   }
 15:  }
 16: } 

The message consumer class :
Note:the connection must be started in order to receive notifications


  1: public class MessageConsumer {
  2: 
  3: private String topicName = "myTopic.Programming";
  4: private String initialContextFactory = "org.apache.activemq"
  5:   +".jndi.ActiveMQInitialContextFactory";
  6: private String connectionString = "tcp://localhost:61616";
  7:   
  8: public void ListenWithTopicLookup() {
  9:      try {
 10:          Properties properties = new Properties();
 11:          TopicConnection topicConnection = null;
 12:          properties.put("java.naming.factory.initial", initialContextFactory);
 13:          properties.put("connectionfactory.QueueConnectionFactory",
 14:            connectionString);
 15:          properties.put("topic." + topicName, topicName);
 16:         
 17:          
 18:           // initialize
 19:           // the required connection factories
 20:           InitialContext ctx = new InitialContext(properties);
 21:           TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx
 22:                            .lookup("QueueConnectionFactory");
 23:           topicConnection = topicConnectionFactory.createTopicConnection();
 24:          
 25:           TopicSession topicSession = topicConnection.createTopicSession(
 26:              false, Session.AUTO_ACKNOWLEDGE);
 27:            Topic topic = (Topic) ctx.lookup(topicName);
 28: 
 29:            TopicSubscriber theTopicSubscriber = topicSession.createSubscriber(topic);
 30:            
 31:            theTopicSubscriber.setMessageListener(new TextMessageListener());
 32:            
 33:            topicConnection.start();
 34:     
 35:      } catch (NamingException ex) {
 36:          Logger.getLogger(MessageProducer.class.getName()).log(Level.SEVERE, null, ex);
 37:      }
 38:          catch (JMSException e) {
 39:    throw new RuntimeException("Error in initial context lookup", e);
 40:   }
 41:  }
 42: }

I change the main class in order to start 2 new message consumers :


  1:  public static void main( String[] args )
  2:     {
  3:         System.out.println( "Hello World!" );
  4:         
  5:         MessageConsumer theMessageConsumer= new     MessageConsumer();
  6:         
  7:         theMessageConsumer.ListenWithTopicLookup();
  8:    
  9:         MessageConsumer OthertheMessageConsumer= new     MessageConsumer();
 10:         
 11:         OthertheMessageConsumer.ListenWithTopicLookup();
 12:         
 13:         MessageProducer publisher = new MessageProducer();
 14:   
 15:         publisher.publishWithTopicLookup();
 16:         try {
 17:             Thread.sleep( 1000);
 18:         } catch (InterruptedException ex) {
 19:             Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
 20:         }

The Result :
[exec:exec]
Hello World!
log4j:WARN No appenders could be found for logger (org.apache.activemq.thread.TaskRunnerFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See
http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Publishing message ActiveMQTextMessage {commandId = 0, responseRequired = false, messageId = ID:Zvika-PC-2639-1370199196674-5:1:1:1:1, originalDestination = null, originalTransactionId = null, producerId = null, destination = topic://myTopic.Programming, transactionId = null, expiration = 0, timestamp = 1370199196906, arrival = 0, brokerInTime = 0, brokerOutTime = 0, correlationId = null, replyTo = null, persistent = true, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = null, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 0, properties = null, readOnlyProperties = false, readOnlyBody = false, droppable = false, text = This is a test message}
Got the Message  TimeStamp: 1370199196906
Got the Message JMS ID : ID:Zvika-PC-2639-1370199196674-5:1:1:1:1
The message:This is a test message
Got the Message  TimeStamp: 1370199196906
Got the Message JMS ID : ID:Zvika-PC-2639-1370199196674-5:1:1:1:1
The message:This is a test message

Each listener got notification about the message that was send .

יום שבת, 1 ביוני 2013

Simple logging with log4j

Getting the log4j jars using maven
The pom file

  1: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2:   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3:   <modelVersion>4.0.0</modelVersion>
  4: 
  5:   <groupId>com.mycompany</groupId>
  6:   <artifactId>Log4jTest</artifactId>
  7:   <version>1.0-SNAPSHOT</version>
  8:   <packaging>jar</packaging>
  9:   <name>Log4jTest</name>
 10:   <url>http://maven.apache.org</url>
 11: 
 12:   <properties>
 13:     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 14:   </properties>
 15: 
 16:   <dependencies>
 17:    
 18:   <dependency>
 19:   <groupId>log4j</groupId>
 20:   <artifactId>log4j</artifactId>
 21:   <version>1.2.17</version>
 22:     </dependency>  
 23:   </dependencies>
 24: </project>
 25: 

The log4j configuration file.
Note: 2 appeanders are declared one for the output of logging into the console and one for output it to file.  
The appeanders to use in each call to logging are declared 


  1: <?xml version="1.0" encoding="UTF-8" ?>
  2: <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
  3: <log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
  4: 
  5:     <appender name="default.file" class="org.apache.log4j.FileAppender">
  6:         <param name="file" value="/log/mylogfile.log" />
  7:          <param name="append" value="false" />
  8:         <param name="threshold" value="debug" />
  9:         <layout class="org.apache.log4j.PatternLayout">
 10:             <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
 11:         </layout>
 12:     </appender>
 13: 
 14:     <appender name="default.console" class="org.apache.log4j.ConsoleAppender">
 15:         <param name="target" value="System.out" />
 16:         <param name="threshold" value="debug" />
 17:         <layout class="org.apache.log4j.PatternLayout">
 18:             <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
 19:         </layout>
 20:     </appender>
 21:   
 22:     <root>
 23:       <priority value="info" />
 24:       <appender-ref ref="default.file" />      
 25:     <appender-ref ref="default.console" />
 26:       
 27:     </root>
 28: </log4j:configuration>

The main file
The main file the demonstarts the use of logging.
Note about the configuration laoding using the DomConfigurator object


  1: package com.mycompany.log4jtest;
  2: 
  3: import org.apache.log4j.LogManager;
  4: import org.apache.log4j.Logger;
  5: import org.apache.log4j.xml.DOMConfigurator;
  6: 
  7: public class App 
  8: {
  9:     private static Logger logger = LogManager.getLogger("myLogger");
 10:   
 11:     public static void main( String[] args )
 12:     {
 13:         DOMConfigurator.configure("log4j.xml");
 14:         logger.info("This is an info!");
 15:         logger.error("This is an error!");
 16:         System.out.println( "Done!" );
 17:     }
 18: }
 19: 

The output
------------------------------------------------------------------------
Building Log4jTest 1.0-SNAPSHOT
------------------------------------------------------------------------


[resources:resources]
[debug] execute contextualize
Using 'UTF-8' encoding to copy filtered resources.
skip non existing resourceDirectory I:\Learn\java\Log4jTest\src\main\resources


[compiler:compile]
Compiling 1 source file to I:\Learn\java\Log4jTest\target\classes


[exec:exec]
2013-06-01 22:48:06,945 INFO  [myLogger] - This is an info!
2013-06-01 22:48:06,946 ERROR [myLogger] - This is an error!
Done!
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.313s
Finished at: Sat Jun 01 22:48:06 IDT 2013
Final Memory: 6M/15M
------------------------------------------------------------------------


sources
http://stackoverflow.com/questions/6358836/log4j-how-to-configure-simplest-possible-file-logging
http://www.dzone.com/tutorials/java/log4j/log4j-file-appender-example-1.html

Controlling the USB FX device from Android tablet

In order to control a usb device I used the USB host api I started to learn the topic using the android missilelauncher demo .

Changing the device_filter.xml file to describe the USB FX2 device.

  1: <resources>
  2:     <usb-device vendor-id="1351" product-id="4098" />
  3: </resources>
  4: 

I want to get a callback notification when  the USB FX 2 device get connected to the android device.


Add to the manifest


  1: <intent-filter>
  2:   <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
  3: </intent-filter>
  4: <intent-filter>
  5:  <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
  6: </intent-filter>
  7: <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
  8:     android:resource="@xml/device_filter" />
  9: <meta-data android:name="android.hardware.usb.action.USB_DEVICE_DETACHED"
 10:     android:resource="@xml/device_filter" />

Register the broadcast activities in the onCreate method


  1: //register for USBFX2 attachment
  2: IntentFilter attachedFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);     
  3: IntentFilter detachedFilter = new IntentFilter(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
  4: registerReceiver(mUsbFX2AttachedReceiver, attachedFilter);
  5: registerReceiver(mUsbFX2AttachedReceiver, detachedFilter);

declaring the BroadcastReceiver for the attached and detached events:


  1: private final BroadcastReceiver mUsbFX2AttachedReceiver = new BroadcastReceiver()
  2:     {
  3:     @Override
  4:     public void onReceive(Context context, Intent intent)
  5:         {
  6:        String action = intent.getAction();
  7:       
  8:          if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
  9:         Toast.makeText(context, "UsbFX2 has connected", Toast.LENGTH_SHORT).show();                  
 10:          }
 11:          if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
 12:            Toast.makeText(context, "UsbFX2 has detached", Toast.LENGTH_SHORT).show();                  
 13:          }
 14:         }
 15:     };

Sources:


http://stackoverflow.com/questions/11191835/receive-intent-action-usb-device-attached-through-code
http://www.ezequielaceto.com.ar/techblog/?p=396 
http://developer.android.com/guide/topics/connectivity/usb/host.html
http://stackoverflow.com/questions/11638216/how-to-make-an-basic-android-usb-host-application

Very simple web api call part 1

Create a new project based of web api template.
The view
Replace all the content of Index.cshtml with the following code

  1: <!DOCTYPE html>
  2: <html lang="en">
  3: <head>
  4:     <title>Routes Web API</title>
  5:     <link href="../../Content/Site.css" rel="stylesheet" />
  6:  
  7: </head>
  8: <body id="body" >
  9:     <div class="main-content">
 10:         <div>
 11:             <h1>All Routes</h1>
 12:             <ul id="RoutesList"/>
 13:         </div>
 14:         <div>
 15:             <input type="button" id="CallWebApi" value="Call web api" />
 16:             <p id="product" />
 17:         </div>
 18:     </div>
 19:       <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
 20:        <script>
 21:          
 22:            $(document).ready(function () {
 23:                
 24:                $("#CallWebApi").on("click", function (event) {
 25:                    // Send an AJAX request
 26:                    $.getJSON("api/values/",
 27:                    function (data) {
 28:                        // On success, 'data' contains a list of products.
 29:                        $.each(data, function (key, val) {
 30: 
 31:                            // Format the text to display.
 32:                            var theRouteName = val.Name ;
 33: 
 34:                            // Add a route for the routes list.
 35:                            $('<li/>', { text: theRouteName })
 36:                            .appendTo($('#RoutesList'));
 37:                        });
 38:                    });
 39:                });
 40:          });
 41:         
 42:        </script>
 43: </body>
 44: </html>

The modal
Create a simple Route modal

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: 
  6: namespace MvcApplication1.Models
  7: {
  8:     public class Route
  9:     {
 10:         public Route()
 11:         {
 12: 
 13:         }
 14:         public int Id { get; set; }
 15:         public string Name { get; set; }
 16:     }
 17: }

The controller
change the values controller as follow


  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Net;
  5: using System.Net.Http;
  6: using System.Web.Http;
  7: using MvcApplication1.Models;
  8: 
  9: namespace MvcApplication1.Controllers
 10: {
 11:     public class ValuesController : ApiController
 12:     {
 13:         Route[] Routes = new Route[] 
 14:         { 
 15:             new Route { Id = 1, Name = "To Scoll" }, 
 16:             new Route { Id = 2, Name = "To Home" } 
 17:         };
 18:         public ValuesController()
 19:         {
 20: 
 21:         }
 22:         // GET api/values
 23:         public IEnumerable<Route> Get()
 24:         {
 25:             return Routes; 
 26:         }
 27: 
 28:         // GET api/values/5
 29:         public string Get(int id)
 30:         {
 31:             return "value";
 32:         }
 33: 
 34:         // POST api/values
 35:         public void Post([FromBody]string value)
 36:         {
 37:         }
 38: 
 39:         // PUT api/values/5
 40:         public void Put(int id, [FromBody]string value)
 41:         {
 42:         }
 43: 
 44:         // DELETE api/values/5
 45:         public void Delete(int id)
 46:         {
 47:         }
 48:     }
 49: }

The Result after clicking the button:
Capture22