Monday, April 16, 2012

Printing bitmaps using CPCL in Android


http://mrpmorris.blogspot.com/2007/08/printing-bitmaps-using-cpcl.html

Thanks a lot. It was really helpful. Zebra documentation is pathetic, no doubt.

I have done a port of this code in Android. I first understood it then, done port for Android.

Hopefully, It will help someone. First convert your image to Black & White(I used Photoshop) which is 8 bits.

ParseBitmap.java
===========

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
import android.widget.Toast;

public class ParseBitmap {

private static final String TAG = "ParseBitmap";
private String m_data;
private Bitmap m_bmp;

public ParseBitmap(Bitmap _bmp){
try{
m_bmp = _bmp;
Log.d(TAG,"Height:"+Integer.toString(m_bmp.getHeight()));
Log.d(TAG,"Widht:"+Integer.toString(m_bmp.getWidth()));

}catch(Exception e){
Log.d(TAG, e.getMessage());
}
}

public String ExtractGraphicsDataForCPCL(int _xpos,int _ypos){
m_data = "";
int color = 0,bit = 0,currentValue = 0,redValue = 0, blueValue = 0, greenValue = 0;

try{
            //Make sure the width is divisible by 8
            int loopWidth = 8 - (m_bmp.getWidth() % 8);
            if (loopWidth == 8)
                loopWidth = m_bmp.getWidth();
            else
                loopWidth += m_bmp.getWidth();
           
m_data = "EG" + " " +
Integer.toString((loopWidth / 8)) + " " +
Integer.toString(m_bmp.getHeight()) + " " +
Integer.toString(_xpos) + " " +
Integer.toString(_ypos) + " ";

            for (int y = 0; y < m_bmp.getHeight(); y++)
            {
                bit = 128;
                currentValue = 0;
                for (int x = 0; x < loopWidth; x++)
                {
                    int intensity = 0;

                    if (x < m_bmp.getWidth())
                    {
                        color = m_bmp.getPixel(x, y);
                       
                        redValue = Color.red(color);
                        blueValue = Color.blue(color);
                        greenValue = Color.green(color);
                       
                        intensity = 255 - ((redValue + greenValue + blueValue) / 3);
                    }
                    else
                        intensity = 0;
                   
                   
                    if (intensity >= 128)
                        currentValue |= bit;
                    bit = bit >> 1;
                    if (bit == 0)
                    {
                    String hex = Integer.toHexString(currentValue);
                    hex = LeftPad(hex);
                    m_data = m_data + hex.toUpperCase();
                        bit = 128;
                        currentValue = 0;
                     
                        /****
                        String dbg = "x,y" + "-"+ Integer.toString(x) + "," + Integer.toString(y) + "-" +
                        "Col:" + Integer.toString(color) + "-" +
                        "Red: " +  Integer.toString(redValue) + "-" +
                        "Blue: " +  Integer.toString(blueValue) + "-" +
                        "Green: " +  Integer.toString(greenValue) + "-" +
                        "Hex: " + hex;
                       
                        Log.d(TAG,dbg);
                        *****/
                     
                    }
                }//x
            }//y
            m_data = m_data + "\r\n";
           
}catch(Exception e){
m_data = e.getMessage();
return m_data;
}

return m_data;
}

private String LeftPad(String _num){
   
    String str = _num;
   
    if (_num.length() == 1)
    {
    str = "0" + _num;
    }
 
    return str;
   }
================================
ZebraDemoActivity.java
==============
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.zebra.android.comm.ZebraPrinterConnection;
import com.zebra.android.comm.ZebraPrinterConnectionException;
import com.zebra.android.comm.BluetoothPrinterConnection;
import com.zebra.android.printer.PrinterLanguage;
import com.zebra.android.printer.ZebraPrinter;
import com.zebra.android.printer.ZebraPrinterFactory;

public class ZebraDemoActivity extends Activity {

protected ZebraPrinter printer;
private Bitmap m_bmp;
private ParseBitmap m_BmpParser;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
options.inDither = false;
m_bmp = BitmapFactory.decodeResource(getResources(),R.drawable.image,options);
m_BmpParser = new ParseBitmap(m_bmp);

        sendCPCLOverBluetooth("00:22:58:36:5C:25");
        //sendCpclOverBluetooth("00:22:58:36:5C:25");
    }
   
   
    private void sendCPCLOverBluetooth(final String theBtMacAddress) {
               try {
                    // Instantiate connection for given Bluetooth® MAC Address.
                    ZebraPrinterConnection thePrinterConn = new BluetoothPrinterConnection(theBtMacAddress);
     
                    // Initialize
                    //Looper.prepare();
     
                    // Open the connection - physical connection is established here.
                    thePrinterConn.open();
     
                    printer = ZebraPrinterFactory.getInstance(thePrinterConn);
                    PrinterLanguage pl = printer.getPrinterControlLanguage();
                    Toast.makeText(this, pl.toString(), Toast.LENGTH_LONG).show();
                    if (pl == PrinterLanguage.ZPL) {
                    Toast.makeText(this, "ZPL", Toast.LENGTH_LONG).show();
                    } else if (pl == PrinterLanguage.CPCL) {
                    Toast.makeText(this, "CPCL", Toast.LENGTH_LONG).show();
                    }
     
                    String TicketID = "23948234";
                    // This example prints "This is a ZPL test." near the top of the label.
                    //String zplData = "^XA^FO20,20^A0N,25,25^FDThis is a ZPL test.^FS^XZ";
                    //It is taking 50 units for each line so forumula is
                    //(1 blank line on top + number of lines in middle +1 blank line on bottom)* 1st argument of ML command = result
                    //put result as 4th argumenet of ! command"
                   
            String str = m_BmpParser.ExtractGraphicsDataForCPCL(0,0);
                    String zplData = "! 0 200 200 230 1\r\n"
                    + str
                    +"PRINT\r\n";
       
                    // Send the data to printer as a byte array.
                    thePrinterConn.write(zplData.getBytes());
                    //Make sure the data got to the printer before closing the connection
                    //Thread.sleep(5000);
     
                    // Close the connection to release resources.
                    thePrinterConn.close();
     
                    //Looper.myLooper().quit();
                } catch (Exception e) {
                    // Handle communications error here.
                    //e.printStackTrace();
                    Toast.makeText(this, e.getMessage() , Toast.LENGTH_LONG).show();
                }
    }

}

Saturday, August 6, 2011

ATM software company milking bank accountholders-Reality and Fiction


I read an article today from following link.

http://www.thenews.com.pk/TodaysPrintDetail.aspx?ID=61106&Cat=3

I think it would be un just that i sit silent that information presented in it is quite distorted. So here are my comments with "Remarks" and "Conclusion". I  have worked in TPS for 5.5 years on ATM switch.

All proprietary means that the software is not compliant to ISO standards that are adopted globally by all the financial institutions

Remarks: :) I can only laugh about lack of knowledge of writer. ISO is standard it doesn't dictate you to make a web service like this. Moreover, TPS message formats are compliant with ISO that's why it is running not only in Pakistan but in many ME, Africa countries. Do you consider these countries fool enough. Again, You don't have knowledge about this so don't speak about it.

Since the software is proprietary, banks and ATM switches like 1Link are not allowed to check, audit or see the software code or even touch the machines that this software is installed on.

Remarks: Joke of the century, 1LINK is going through PCI audit and i am quite sure that you only know that PCI used to be slot in PC mother board. So, dude get some knowledge about it. Secondly, softwares are installed on bank's machines and they are in bank premises and under bank control like any other software. Since it is not a open source product like many other so you can't expect to see its code. If you are so desperate in seeing TPS source codes get a job there if you have enough talent :)

TPS is stealing a huge amount of money on a daily basis from bank accountholders. How is this possible? Hundreds of thousands of ATM transactions are made every day. If a virus or special code takes out just one paisa for each transaction, the account holders obviously cannot suspect any wrongdoing. But the company manages to steal a huge amount of money in this way every day from bank accounts

Remarks: Banks can sue you for this dude, Ever heard of "Day end"? When this thing happens core banking in banks post all accounting entries in respective heads and they all should balance all credit must be equal to all debit. This is basic accounting. Again, disappointing who let you write this article :)


He further said that after initial investigation it was believed that it was a mega scam in the banking sector

Remarks: Monopoly is something different than scam. Microsoft is facing multiple suits like this. But if it were a scam and i take 1 paisa out of your account daily then how the hell can day end complete in banks. Go and learn this from some account student of FA.


Sources further said that TPS bribed banks’ IT departments to install its software in banks and avoid audit. Other problems faced by banks due to this monopoly is that when things go wrong they have to wait for long periods for TPS to fix them. It charges them for every change or support. These charges to the banks are passed on to the accountholders as different fees by banks.

Remarks: Suppose even if TPS bribed then i think those involved in those bribes should be caught :). Dude this is not a sarkari bank wehere TPS softwares are installed. TPS software competes with ACI, S1,Euronet etc and then get in. I feel ashamed how on earth you are allowed to right in "THE NEWS" and no body audits you.

They said banks do not have any relationship with TPS, but they still have to pay charges to TPS. The reason is that TPS claims that they own the software installed at 1LINK (the main ATM switch) for bill payment and each entity (any bank) who wants to get connected with 1LINK for bill payment, must pay a licence fee to TPS.

This “system” has been put in place by 1LINK’s initial founders and board and is still prevalent due to the extraordinary bribes paid by TPS to board members of 1LINK. State Bank officials have also been pat of this scheme, sources said.

Remarks: Once again foolish statement. 1LINK is a business entity and they charge not TPS. Again, you can't critize business policy. It would be like i will start shouting why Oracle Database is charged per core not per processor?I think you don't even know what is core and what is processor.


Conclusion: I have worked in TPS for 5.5 years on their main switching products and I feel very sorry to say that writer doesn't even know the basics of accounting and trying to defame a company which is giving pride to Pakistan. Nonetheless, It won't hurt TPS because every knowledgeable person in the field(Banks,Financial Institutions) know TPS worths not only in Pakistan but in other countries. It has competed and replaced many International giants in other countries and If we agree to hypothesis placed by writer then how an earth this software gets place in countries like UAE, Qatar, Kuwait, France, etc,etc.

We are in the habit of degrading our own things like writer did without knowing it completely. Rather than appreciating a company which is home grown and competing with giants not only in Pakistan and outside Pakistan we are trying to insult it.

Last point, Check out ATM services offered by ACI and other giants banks in Pakistan were not even in position to get their own ATM switch if they were to ask them back in late 90s.
I assure one thing very clearly no banking software can steal your money, its a Bank. Everything is present and reconciled. You can always check your statement to be sure. Be it Avanza, be it TPS, be it any other company.

Sunday, February 20, 2011

Art of becoming a good manager

Alright, so you get a team of programmers under you and you have been declared their manager. Wow!
So, if the above mentioned incident was an outcome of an accident or you have travelled a long road to reach here rules of game will remain the same.
Following are few things I have learned over the time from my personal experience or from colleagues having same role.
For many of us out there this is common sense but unfortunately we have common things missing.
1.       A Happy Smiling Face – I know you are not on a public dealing job but this is the very basic rule to be a good leader.  Whenever you approach your juniors or a junior approaches you, talk with a pleasant smiling face. This way you are giving him/her confidence like a good doctor does with his/her patient and then they speak out whatever they feel like.

2.       Never act like Corporate Feudal – Title of this advice says it all. Be humble and kind towards your juniors.  Don’t boss them; Make them realize that they are owners of their work. You are here to help and need their help to finish this task.

3.       What can I do for you Sir/Madam – For some people it looks odd if you ask your junior “May I be of any help” regarding work or any other matter. This shows that you are not a daddu (frog) manger but a multi dimensional personality having firm observations not only on work but on other matters which affect their work performance.
I have seen bosses making tea or bringing lunch/dinner, carrying hardware at times for their busy teams at work because they want to help. Remember your team is watching all this. Being a manager it is your responsibility to let your team focus on work and you do provide all the miscellaneous items support.

4.       Superstar treatment– Fame and Money always attracts, this is in human nature. I know you can’t give them a heavy pay check by yourself (again, lots of corporate theory J ). At least you have control over something which you can give them. Treat them like superstars; praise them by putting emails to higher management and to their colleagues about their achievements. If your budget affords I recommend giving away an ice cream, samosa, chips party on their achievements.

5.       Embrace Change– It’s always hard to swallow change. Don’t be hardliner, remember you are a manager and your task is to get best out of your resources. Let them come up with an idea, always ask them to bring a new idea. Get rid of your code entropy disease.  They might be suggesting something which really improves your things.
If you fail to convince them that their idea can’t work, try to give them time in which they can work out themselves or you do as they are suggesting in spare time and let them see how it collapses.  Developers are egoistic mostly and sometimes they tend to make technical things matter of ego in their early professional life.

6.       Say No to Workaholic attitude – It’s quite common that you will see juniors around who wants to work and work only. In short term you might consider it a benefit for yourself or your company but you are heading towards a disaster. Never ever allow such an attitude or approach of your juniors.
In short term this looks very attractive that what a dedicated resource sir jee! But, you are heading towards a disaster. If resources keep working like this un necessarily they will lose interest or burn out.
Tell them to have time for themselves, family and friends. Suggest them activities they should do after office hours.

7.       Successor Planning– Many of us don’t believe in doing this, they are afraid if they transfer all the information what their role will be, what their company would do with them. If you have this fear that transferring knowledge or control will make you retire then it means you don’t deserve where you are sitting today because you are afraid of kids whom you taught.
Until or unless you are working in a Seth (sole proprietor) company or poor corporate surrounded by politics then you don’t have to behave like this. Remember experience can’t be replaced.

8.       Party Time– No matter your company sponsors event or not, it’s not a complex thing that you and your team goes out for some activity like having lunch together on a weekends or go out on dhaba for tea in evening before going home and have some chit chat. This is a good way of learning minds of your resources and they also have chance to discuss general things with you.

9.       Have a break, Have some off days– Ask your juniors to plan and take annual leaves to have some break from a monotonous routine of office. You might have heard from your juniors I get bored at home, even then don’t take this excuse and give them a break.

10.   Patrolling– Kindly get up from your seat at least once a week during office hours suitably in late part of 1st half or 2nd half and visit desk of each of your team members to discuss how is it going, is everything fine, you can ask them about their studies or any activities they do.

11.   Act as Air Bag– I hope you understand what I mean. During a pressure situation, collapse, screaming clients act as a vacuum chamber for team. If you can’t shield them from all this I bet their mind will be distributed between all this and problem at hand.
Always ask them to do their best in pressure situations and keep environment light. Never ever show a tense face to them, this will definitely cause un rest, remain calm and composed.  Try to get best out of worst. Remember point-7(Successor Planning), what you do in front of juniors today they will do it when they will become managers and you have taught them all.
If you start postmortem or start shouting then this will create a very negative impression. Remember you are a manager and your job is to manage. Let them do technical work and you focus on keeping things in control. You will always have time to do postmortem of situation.

12.   Courtesy– It’s all about manners and courtesy. If your resources or someone in their close acquaintance got ill and you know that they are out of office because of this then give them a courtesy call or send them an SMS asking if you can be of any help.
13.   Divide Pizza Equally– Always ensure that everyone in team gets equal chances of growth, R&D projects, Trainings, Deputations. If you fail to do so then so you might face a serious problem where someone will get up and say good bye and thank you. Remember its not a mason's job, it takes lots of hard work to make an skilled worker. So, Keep your eyes and ears open.

Saturday, August 28, 2010

Smart Driving

While driving on Karachi roads when traffic is jammed and you see lots of common things around. There is one thing which I commonly observe. We see an ambulance is trying to make its way out of this and carrying a patient very often. Its siren is buzzing loud and even we hear ambulance making announcement "rasta dain,...rasta dain"..

But, unfortunately what I have observed in 8 out of 10 cases that people whose vehicles are ahead of them are failing to clear a path out for ambulance. Reasons and solutions are quite simple.

1) Those who are privileged enough to have four wheelers with windows closed and A/C running with a sweet melody playing often turns a deaf ear to this situation as if something very ordinary is happening outside. 
It is not their fault, it is just their lack of maturity. They are blessed but don't know responsibilities they carry with these blessings.So, If you are blessed like this please keep an eye on your back and side mirrors to have an idea if you see an ambulance trying to make its way. If you start shifting lane believe me that vehicles besides you will start doing the same.

2) Those who are riding on bikes often thinks that they are on such a small thing and they also don't need to move to other lane. Don't make this assumption, because I have seen other bikers to make this assumption and collectively many bikes create a congestion point. So, Realize the situation and get aside.

3) Those who are driving long vehicles like buses, trucks, etc. I know they don't get a chance to read this writing or hardly anyone reading this blog can see such a driver in person and tell him what I have observed :)
So, for them I have seen some people doing the trick so car drivers and bikers can do the same. I have seen bikers coming beside to buses and shouting to get aside because of ambulance. I have seen cars blocking their way to clear out a path for ambulance.

4) Don't be so smart to run behind an ambulance and taking advantage of a clear lane. Since you rarely see ahead of a Suzuki Bolan/Hiace(ambulances) and if they shift lane you will be hitting in some one's vehicle. 

Sometimes when I travel in a Taxi and driver is not concerned about the ambulance coming behind it I ask him to please shift lane or at least try to shift. Sometimes I got the answer "bhai yeh jan bojh k bhi aisay kartay hain ya pher itna jam hai kahan jaaon ya yeh tou gorment/traffic police ka kam hai". 

Imagine yourself lying in that ambulance. Do whatever you can, don't start justifying or throwing ball in other people courts. We have enough of it as a nation, there are certain things which we can do. So, act immediately and give way to ambulances. 

Be a responsible driver.

Pastry from a magnifying glass

I have met many fresh graduates from computer science background in my acquaintance and same type of question is being asked by them. "What kind of job shall I do or look for once I graduate".

So, I thought I will write somewhere what I used to tell them and from next time I will advice them to read it then we will discuss.

Let me quote an example, "A pastry from a magnifying glass". You must be saying what kind of pathetic answer is this. Well, keep on reading you will realize that this is the answer.

Remember few points

1) Pay check.You existing pay check speaks your market worth.It tells your next employer that you were important enough that company was paying you this amount. So, don't get fooled by these words "you are going to make a rocket but you will be paid less because we are letting you work in such a wonderful and unique area that no one in market is doing". You are not out there for "Charity".

2) Grooming. If you get to work in a garage like environment you will never learn art of how to talk to your senior,peers,clients, how to dress yourself etc etc. Its all about work etiquette's. So, don't work in a garage. This will make you techie only but you will lack basic soft skills.

3) Stability.There is a difference between doing job and fulfilling a hobby. There are few lucky people who are actually doing what they love to. Because not everyone is blessed this much :)
Work for a company which is stable enough not a jerk where few investors are tolling with their "Great Ideas" and when they get fed up they say "Thank you for working with us".

4) Learning. Don't go for monotonous work. Try looking out for work where you got a chance to learn tools, technologies, concepts, professional work methodology. If you run into an environment where you don't see new ideas, tools, technologies and methodologies at work then your basis will be made in wrong direction.It takes a lot of efforts to write a quality software(Designing, Coding, Optimization[Profilers,Code Analysis],QA, Release Management,etc). Try learning new things on your own and discuss with your peers,team leads if that can improve your work quality.

5) Next Possible Move.Its not wise to sell "spectacles" where everyone is blind. So, Calculate your next possible move, means where you would go after this. I know some intellectuals would come forward and say that they are working on it because they are "lateral thinkers" :). For them I have simple answer, Don't do job then become an entrepreneur.

That's what I can tell from my little experience. I have been through all this. I know its not possible to get everything in your plate at once, but keep trying for it. At least go for one which has maximum in it and remove "Magnifying glass" while you are asked to view a pastry :)

That's all for today.

Wednesday, August 25, 2010

Most abused words - Critical, Urgent, Important, High Priority

Most of the people who are working in private organizations are quite used to of hearing and reading words mentioned as heading of this writing.

We normally hear these words from clients, business development department and marketing departments and last but not least by managers like myself.

I use these words to emphasize my sub ordinates of importance of situation or matter in hand. But, do we ever think how badly we abuse these words and they are losing their impact day by day. It’s like saying “Pakistan tareekh k aik nazuk daur say guzur raha hai”. We all have been hearing it since we were kids.
Do we really think once the situation has passed, if it was that critical that I declare it as a TSUNAMI? I guess no. If we think on these lines we could see how many false alarms we generate every now and then and how badly we are destroying the essence of these words.

It’s all about handling situation effectively. I sometimes realized that if I can handle pressure myself rather than running myself in the crowd and saying “Bhagooooooo”. It was my fault and I apologize for the ones who suffered due to my miscalculation.

One of my friends was telling a story about an advertising campaign for which he worked. Now, Analyze this situation tomorrow there will be a major strike in city by some of the political party and he was instructed to keep his field workers out in city all night to put on all the advertisement banners by morning considering situation is getting worse in city. Now, see how critical it was. The person instructing it could have handled situation on his own but he didn’t and he just passed on what he received.  The fun part here no one dared to come on street on strike day even they guy who mentioned it to be a critical activity.

Medicine is the most critical of all kinds of services being provided.  But, I have hardly seen any urgency or criticality in this area. I have seen patients in life and death situations in ICUs even my father was in such situation. Their doctors didn’t come at the time of emergency and people are told that on duty doctor will take care of your patient. In worst case they will make a call to respective doctor. In some cases when you have good terms with Doctor they can come in but mostly it is not case. I ask myself this question that the most important area is the most neglected one. We are ready to save an advertising campaign, recovering an email server from crash but not a human life.

These words should be used with caution and as a first step we should analyze if it is really a critical situation. If they are really critical we should pass on as much knowledge to receiver(s) so that they also what is happening in background otherwise they will destroy your image in front of receivers.