Wednesday, October 30, 2019

LED Strips Programming (Arduino)

Today, I am going to share my experience on the LED Strips programming using Arduino. It will be fantastic to decorate on Christmas nights, which you can program each LEDs as required like we could create a cool animation.

This article does not go into detail. This will just give you the idea on how we can program LED strips and you can program the lights according to your need.

Let's begin, we need the following items before we begin the programming.

1) Arduino
2) Power Source (10 V)
3) Wires
4) LED Strip

We connect the power source to one end of the led strip. Normally positive wire of the strip is red, and the negative is white. The white is grounded with the ground of the strip. Strip has also cables to be connected to the Arduino. GND should be connected to the negative power supply. Note that the green color cable is used for the color signal which we normally connect to PIN 7 of Arduino.

If you are using an external 10V power supply, we connect the positive to the red and negative to the white one. NEVER connect the red one into the 5V pin of the Arduino which burns it. I have burnt 3 Arduino by mistakenly connecting this 10V in 5V pin in Arduino.

So, the connection will be like this:

1) Without external power
If we DON'T want to use external power, then we need to use an Arduino +5V pin as a power supply to the LED strip. Please note that, because Arduino can't deliver enough power, we have to compromise the brightness of the LED Strips.

The connection diagram will be as follows:


2) With external power supply
If the Arduino power is not enough for the LED strips, we need external power supply. I have used 15V 5A power supply.  Please be very careful while connecting external power supply. Note that if you mistakenly connect your +15 V in the +5V pin, then you will burn your Arduio which I did 4 times!
So, if you using an external power supply, never connect the red (positive) +15V to the Arduino. But the negative of the power supply (normally white line) should be connected to the GND of the Arduino. The PIN 7 should be connected to the green line DIN of the strip. 
Please look into the connection diagram

Please note that the +15V red line is not connected to the Arduino.

Now we come to our actual task: programming. Before we start we have to install the needed libraries.

We need Adafruit_Neopixel and optional Tinkerkit libraries. Adafruit library is used to actual programming while Tinkerkit libraries make it easy to read sensor values because we are using sensors to control the led lights.

The code is made downloadable from git repository:


This example code is just a kind of animation I have created. But we can use the power of
Arduino to define cool animations in your own way.
Just try yourself :)

Monday, April 22, 2019

Arduino Basics

Arduino is a simple, programmable micro-controller.  In this article, I am gonna write some tips which make programming with Arduino more simple.

1) Installation 

The first step will be the installation of Arduino from here:

https://www.arduino.cc/en/Main/Software

You, normally select the latest version for download, not nightly build versions.

I downloaded 1.8.9 version.

Extract the downloaded compressed file into /opt/arduino (for example). Just run the install.sh file inside the extracted Arduino folder.


2) Settings for Visual Studio Code

After installation is complete, we have to carry out some settings in visual studio code. First, install the Arduino extension and after installation is complete, restart IDE. Then we create a workspace folder.

~/workspace/arduino /src/Project1

Now, we open the arduino folder from VSCode IDE. Now, using

CTRL+SHIFT+P

A: Arduino:BoardConfig
B: Arduino:Initialize
C: Arduino:Select Serial Port

The final step is to define the build folder in arduino.json created in the root directory.

 "output": "build",

This is, I guess, automatically created. But to be safe, add this line.

3) Create a Program

The most interesting part is here.

Create a new program example.ino  with the following contents

void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}


Then we first verify the correctness of the program. And then upload the program.

Verification:  CTRL+SHIFT+P => Arduino:Verify  (Shortcut: CTRL+ALT+R)
Upload: CTRL+SHIFT+P => Arduino:Upload (Shortcut: CTRL+ALT+U)


Problems faced

While uploading I faced the following problem

An error occurred while uploading the sketch
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied

I did not know how secure is this, but I made the terminal readable and writable for all. And restarted IDE, then it worked! I ran the following command from the terminal.

sudo chmod a+rw /dev/ttyACM0 

Now, we can use the power of visual studio code to develop Arduino programs. 

Note: Because we can not place multiple files and run. To achieve this we create a folder structuer inside src folder of root.  For example:

ArduinoRoot
.....src
----------Project1
----------Project2
-------------------SubProject1










Monday, March 11, 2019

Simple Windows Installer

For windows system, is there any possibilities of creating a packaged installer like DEB in Ubuntu system? I have carried out some research and studies to find out the solution for this. Although there are possibilities to create a packages exetutable installers using different tools. After thorough comparison and reviews I got to conclusion that NSIS (Nullsoft Scriptable Install System) provides the best solution for that. It is really simple, everything is scripts, also very scalabale and powerful.


So, lets get started!

I create a basic installer using some files and scripts as resources. Please note that there are many possibilities we could add more functionalities. This article describes a very basic example on how we can create a simple installable packaged executable which can be deployed for installation.

We just write scripts into a file with extension *.nsi and installer is created from the scripts defined in the file. There are possibilities to create shortcuts, copy resources, define UI and many more. 

The first step to begin with is to install NSIS software which can be found at

https://sourceforge.net/projects/nsis/

After installation, we have to install NSIS plugin for visual studio code. Then, we have advantage of autocompletion and easy compilation. 

Writing a NSI file is divied into different blocks with their specific tasks and all blocks are run sequentially(there are some exceptions like Uninstall block runs at the time of uninstalling the application.) 

1) Definition Block

This block defines different variables which we wanted to define here. We can define a variable using

!define MUI_PRODUCT "Frietec Google Service"
!define AUTHOR "paudekri@frietec.com"

2) Basic Block

The basic block is very important because we define the Name, output file and install directory where the application is supposed to be installed. For example

Name "${MUI_PRODUCT}"
OutFile "FE-Google.exe"
InstallDir "C:\Frietec\${MUI_PRODUCT}"

3) Macro Block

We can create installed without macro block, but using macro block makes further improvements such as greater looking GUI and so on. A sample macro block is 

!include MUI2.nsh
!define MUI_ICON "Resources\installer.ico"
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_LANGUAGE "German"

4) Section Block

The section block backbone where we define the processese of installation in different sections. We define scripts to copy resources or create uninstaller and define scripts and so on. 

For example:

Section "install" Installation
  # Copy scripts 
  SetOutPath $INSTDIR
  #File Scripts\Calendar.bat
  #File Scripts\Drive.bat
  #File Scripts\Email.bat
  File /r Scripts scripts
  SetOutPath $INSTDIR\resources
  File Resources\email.ico
  File Resources\drive.ico
  File Resources\calendar.ico
  File Resources\installer.ico  
  WriteUninstaller $INSTDIR\uninstall.exe
SectionEnd

Section "Shortcuts"
  CreateDirectory "$Desktop\${MUI_PRODUCT}"
  CreateShortCut "$Desktop\${MUI_PRODUCT}\Uninstall.lnk" "$INSTDIR\Uninstall.exe"
  CreateShortCut "$Desktop\${MUI_PRODUCT}\Shortcut to Email.lnk" $INSTDIR\scripts\"Email.bat" Icon $INSTDIR\resources\"email.ico"
  CreateShortCut "$Desktop\${MUI_PRODUCT}\Shortcut to Drive.lnk" $INSTDIR\scripts\"Drive.bat" Icon $INSTDIR\resources\"drive.ico"
  CreateShortCut "$Desktop\${MUI_PRODUCT}\Shortcut to Kalendar.lnk" $INSTDIR\scripts\"Calendar.bat" Icon $INSTDIR\resources\"calendar.ico"  

  CreateDirectory "$SMPROGRAMS\${MUI_PRODUCT}"
  CreateShortCut "$SMPROGRAMS\${MUI_PRODUCT}\Uninstall.lnk" "$INSTDIR\Uninstall.exe"
  CreateShortCut "$SMPROGRAMS\${MUI_PRODUCT}\Email.lnk" "$INSTDIR\scripts\Email.bat" Icon $INSTDIR\resources\"email.ico"
  CreateShortCut "$SMPROGRAMS\${MUI_PRODUCT}\Drive.lnk" "$INSTDIR\scripts\Drive.bat" Icon $INSTDIR\resources\"drive.ico"
  CreateShortCut "$SMPROGRAMS\${MUI_PRODUCT}\Kalendar.lnk" "$INSTDIR\scripts\Calendar.bat" Icon $INSTDIR\resources\"calendar.ico"
SectionEnd

Section "Uninstall"
  Delete $INSTDIR\uninstall.exe
  RMDir /r "$INSTDIR\*.*"
  #Delete $INSTDIR\*.*
  RMDir $INSTDIR
  
  Delete "$Desktop\${MUI_PRODUCT}\*.*"
  RMDir "$Desktop\${MUI_PRODUCT}"
  Delete "$SMPROGRAMS\${MUI_PRODUCT}\*.*"
  RMDir "$SMPROGRAMS\${MUI_PRODUCT}"
  #Delete "$Desktop\FE-Google\Shortcut to Kalendar.lnk"
SectionEnd


5) Function Block

The block block is where we define functions. A typical usage is to display messagebox when installation success or uninstallation is done.

For example:

#Function that calls a messagebox when installation finished correctly
Function .onInstSuccess
  MessageBox MB_OK "You have successfully installed ${MUI_PRODUCT}. Use the desktop icon to start the program."
FunctionEnd
  
Function un.onUninstSuccess 
  MessageBox MB_OK "Sie haben erfolgereich deinstalliert=> ${MUI_PRODUCT}."
FunctionEnd


The compilation creates an executable installer file in the same directory. We can execute this file to get installed. Similarly we can install it by clicking the unistall link in the installation directory or can be defined as a short for simplicity.

The full project is available at the following github location:

https://github.com/krishna444/MyWindowsInstallaer.git




Friday, February 22, 2019

Spring Boot with GWT using gradle build

Today I am going to write an interesting concept, which will be quite useful to quickly start and deploy a  big project without worrying about any javascript complexities.

It is well accepted that Spring Boot is very popular backend framework and I have to say, it is not quite supportive for front-end development. For that we have to use frontend development system using Javascript, because Javascript is the only option. And the communication to the server using Javascript makes less maintainable code. Also, using GWT, we write both server and client side program using a single programming language Java, which makes it a very scalabale and maintaible project. That's my experience because I use a framework called echo(echo.nextapp.com) which is quite stable and very very maintainable.

Lets begin implementing Spring boot with GWT. It seems a bit complicated, have a patience because end result is very interesting.

I am using eclipse IDE for development. So, I assume you have already installed it including JDK(1.8 is preferrable). Please be sure the installed gradle version is greater or equal to 4.0 for SpringBoot to work.

Step 1: Project Creation

Now create a new gradle project from eclipse IDE or using gradle command.

gradle init --type java-library


and just import created project into eclipse. This is the basic project project. We have modify this project.


Step 2: Configuration

We carry out build configuration in build.gradle file. It is recommended to remove all the contents and use the following content:
//build.gradle
buildscript{
repositories{
mavenCentral()
}
dependencies{
classpath 'org.wisepersist:gwt-gradle-plugin:1.0.6'
}
}

plugins{
//Required for springboot
id 'java'
id 'org.springframework.boot' version '2.1.3.RELEASE'
}
apply plugin: 'gwt'
apply plugin: 'io.spring.dependency-management'

sourceCompatibility =1.8
targetCompatibility=1.8
def GWT_VERSION='2.8.2' //latest version

repositories{
  jcenter()
}

//not needed (if you use default values). The following values
// are default values, so not necessary.
sourceSets{
main.java.srcDir "src/main/java"
main.resources.srcDir "src/main/resources"
test.java.srcDir "src/test/java"
test.resources.srcDir "src/test/resources"
}

dependencies{
//Just add this 4 libraries for gwt
compileOnly("com.google.gwt:gwt-user:${GWT_VERSION}")
    compileOnly("com.google.gwt:gwt-dev:${GWT_VERSION}")
    compileOnly('org.fusesource.restygwt:restygwt:2.2.3')
    compile('javax.ws.rs:javax.ws.rs-api:2.1.1')
    
    //Spring libraries
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-jetty')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    compile('org.springframework.boot:spring-boot-starter-web'){
      exclude module: 'spring-boot-starter-tomcat'    
    }      
}
 //gwt configuration
 gwt{
     gwtVersion=GWT_VERSION
     modules 'com.kpaudel.frontend.SpringBootGwt'
     maxHeapSize="1024M"
 }


//package
task copyGWTCode(type:Copy){
  //from compileGwt.outputs
  from file("${buildDir}/gwt/out")
  into file("${buildDir}/resources/main/static")
 }

 copyGWTCode.dependsOn compileGwt

 bootJar{
  dependsOn copyGWTCode
  doLast{
  mkdir "${buildDir}/target"
  setDestinationDir(file("${buildDir}/target"))
  copy()
  }

 } 

Step 3: Create a GWT module

It is important step. Here we provide the path of the module definition file. This file defines all GWT related information.  There can be multiple modules,  which should be first define in build.gradle file(in gwt block) above. In packaging system, suppose we create a package called

com.kpaudel.com.frontend

Then module information file is located in the package(the file extension of module file name is always *.gwt.xml). We create a module definition file name with the following contents:

   

So, we create two packages, one for client and one for shared.

com.kpaudel.frontend.client This package for client only files
com.kpaudel.frontend.shared This package for shared files(both client and server)

Like we defined entry point class in module definition file above, we create a Java File as entry point:
Here is a very simple example:

//SpringBootGwt.java
package com.kpaudel.frontend.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

public class SpringBootGwt implements EntryPoint {

@Override
public void onModuleLoad() {
RootPanel.get().add(new Label("Hello World"));
}
}

Step 4: Compilation

What we did so far can convert our java files into javascript file using the following gradle script in the project root path.

./gradlew compileGwt

The compiled javascript files are located in build/gwt/out/frontend folder. The folder name frontend comes from the module name defined in the module definition file.

Step 5: Server Stuffs

Now, we can do server stuffs now. Because we are backed up by very powerful spring framework, so we can do whatever we want using this technology.

Step 6: Packaging

Packing stuffs into a bundle jar is a bit complicated in the sense that we have to include some scripts in build.gradle file. Please have a look at the last lines of build.gradle file.

Sunday, February 10, 2019

Thursday, January 17, 2019

Windows10 Licencing

Licencing is a headache, if you don't do it, even if you paid for licence, you can not use a product. This short article touches the surface of licencing in Windows 10.

View Installed Licence

Yes, to use Windows 10, we need a valid licence. Windows stores this licence somewhere in your system, so that, it normally automatically activates your system and you do not need licence again. Sometimes, this is not enough because we need to manually activate the system and in this situation, we need the actual licence.

Windows hides the licence from viewing(only last 5 letters are shown), that means we need to get the script which shows the installed licence in the system.

I got a working Visual Basic Script which shows the installed licence in the system.

File: GetProductKey.vbs
(script source: https://www.winhelponline.com/blog/view-your-product-key-windows-10-8-7-script/)
Option Explicit  
 
Dim objshell,path,DigitalID, Result  
Set objshell = CreateObject("WScript.Shell") 
'Set registry key path 
Path = "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\" 
'Registry key value 
DigitalID = objshell.RegRead(Path & "DigitalProductId") 
Dim ProductName,ProductID,ProductKey,ProductData 
'Get ProductName, ProductID, ProductKey 
ProductName = "Product Name: " & objshell.RegRead(Path & "ProductName") 
ProductID = "Product ID: " & objshell.RegRead(Path & "ProductID") 
ProductKey = "Installed Key: " & ConvertToKey(DigitalID)  
ProductData = ProductName  & vbNewLine & ProductID  & vbNewLine & ProductKey 
'Show messbox if save to a file  
If vbYes = MsgBox(ProductData  & vblf & vblf & "Save to a file?", vbYesNo + vbQuestion, "BackUp Windows Key Information") then 
   Save ProductData  
End If 
 
 
 
'Convert binary to chars 
Function ConvertToKey(Key) 
    Const KeyOffset = 52 
    Dim isWin8, Maps, i, j, Current, KeyOutput, Last, keypart1, insert 
    'Check if OS is Windows 8 
    isWin8 = (Key(66) \ 6) And 1 
    Key(66) = (Key(66) And &HF7) Or ((isWin8 And 2) * 4) 
    i = 24 
    Maps = "BCDFGHJKMPQRTVWXY2346789" 
    Do 
           Current= 0 
        j = 14 
        Do 
           Current = Current* 256 
           Current = Key(j + KeyOffset) + Current 
           Key(j + KeyOffset) = (Current \ 24) 
           Current=Current Mod 24 
            j = j -1 
        Loop While j >= 0 
        i = i -1 
        KeyOutput = Mid(Maps,Current+ 1, 1) & KeyOutput 
        Last = Current 
    Loop While i >= 0  
     
    If (isWin8 = 1) Then 
        keypart1 = Mid(KeyOutput, 2, Last) 
        insert = "N" 
        KeyOutput = Replace(KeyOutput, keypart1, keypart1 & insert, 2, 1, 0) 
        If Last = 0 Then KeyOutput = insert & KeyOutput 
    End If     
     
 
    ConvertToKey = Mid(KeyOutput, 1, 5) & "-" & Mid(KeyOutput, 6, 5) & "-" & Mid(KeyOutput, 11, 5) & "-" & Mid(KeyOutput, 16, 5) & "-" & Mid(KeyOutput, 21, 5) 
    
     
End Function 
'Save data to a file 
Function Save(Data) 
    Dim fso, fName, txt,objshell,UserName 
    Set objshell = CreateObject("wscript.shell") 
    'Get current user name  
    UserName = objshell.ExpandEnvironmentStrings("%UserName%")  
    'Create a text file on desktop  
    fName = "C:\Users\" & UserName & "\Desktop\WindowsKeyInfo.txt" 
    Set fso = CreateObject("Scripting.FileSystemObject") 
    Set txt = fso.CreateTextFile(fName) 
    txt.Writeline Data 
    txt.Close 
End Function

After saving this content into the file, we can execute the file which shows the installed licence.

 How to Activate Licence (slmgr)

Windows has given us a very useful tool called slmgr.vbs which is used to view licence information and many other licence related operations.

Please have a look at this article for detailed information regarding slmgr tool:

https://www.howtogeek.com/245445/how-to-use-slmgr-to-change-remove-or-extend-your-windows-license/

I have listed some useful commands using slmgr.vbs tool.

a) slmgr.vbs /dli (Display licence information)
b) slmgr.vbs /dlv (Detail licence view)
c) slmgr.vbs /xpr (Expiration date)
d) slmgr.vbs /upk (Uninstall product key) => Restart required.
e) slmgr.vbs /cpky (Clear product key from registry only)
f) slmgr.vbs /ipk ####-####-####-####-#### (Install product key)
g) slmgr.vbs /ato (Activate online)
h) slmgr.vbs /dti (Displays confirmation Id) => this id should be given to support for offline activation, then support gives your activation_id.
g) slmgr.vbs /atp activation_id (Activate with id)




Friday, January 11, 2019

Basic Git commands

1. Cloning a git branch

git clone -b solution https://github.com/SNCodingChallenge/stm_challenge_krishna_paudel.git

2. Change push repository

   First clone the git project into your local:
   git clone git@kpaudel.com.np:/opt/git/MyProject.git
 
 Go into MyProject folder and hen remove the .git folder which clears out all the old information. Run the command:

git init 

Which regenerates git information. Now we add remote repository to push:

  git remote add git@mysansar.com:/repos/git/MyNewProject.git 

Now verify:

  git remote -v 


3. Create a new repository in the server

 Create a folder MyNewProject.git into Server repository.
 Go into the directory and execute

   git init --bare

Give access rights to the git user. (Normally we set the owner of the directory as git)

4. Push to the remote repository

git push origin master

5.Commit changes to the local repository

git commit -m "Message" .

6.Merge updates from a branch

git pull [origin branch]

Example:
a) Merging from the same branch
git pull

b) Merging from master branch
git pull origin master

Note: If sometimes, the pull merging gives the following failure:
"refusing to merge unrelated histories"
Then the following command will be useful.

git pull origin master --allow-unrelated-histories

7. Disable http ssl verification

We need this when we create a certificate by ourselves for our private purpose. In that situation, we have to disable SSL verification or simply use ssh. 


git config --global http.sslverify "false"

8. Store GIT credentials

Sometimes we need this feature if you are tired of providing the username and password while executing the git command. The solution for this is to store credentials,

git config --global credential.helper store

It stores the credential and you never need to provide the username and password.

There are some options too:
git config --global credential.helper 'cache --timeout=600'
git config --global credential.helper cache


10. Display the branch name in the terminal

If we display the branch name in the terminal, it helps us to know which branch we are working on and also prevents mistakenly working on other unintended branches.

I found the script to run to activate this feature in the terminal. 

# Show git branch name
force_color_prompt=yes
color_prompt=yes
parse_git_branch() {
 git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
if [ "$color_prompt" = yes ]; then
 PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git_branch)\[\033[00m\]\$ '
else
 PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)\$ '
fi
unset color_prompt force_color_prompt

Just save this file in "git-branch-name.sh" in your preferred location and run this at the time the system starts.
To run this script while the system loads, we need to append the following lines in the .bashrc file. 
...
# To display git branch name in the terminal
if [ -f /Backup/scripts/git-branch-name.sh ]; then
   . /Backup/scripts/git-branch-name.sh 
fi 
...