There are many examples online as to how to construct one's own client / server socket connection in C++, but unfortunately they do kind of take for granted that you know your stuff. Here I will share my working source code which satisfied the questions I asked but could not find:
For this, I used Linux Mint 16 in VirtualBox with a Bridged Network Connection (my virtual machine had it's own IP address assigned by the local network router). Also used a C/C++ Eclipse IDE and the GCC Compiler, here is my server code: (the client side that tested this is in C# on the host OS, Windows 7)
#include <iostream> // time, ctime
#include <cstdlib> // exit
#include <cstdio> // snprintf
#include <unistd.h> // gethostname, write, close, sleep
#include <netdb.h> // socket, htonl, htons
#define MAXHOSTNAME 256
void* memset(void* b, int c, size_t len);
int main()
{
int listenfd = 0, connfd = 0, n;
struct sockaddr_in serv_addr;
const int BUFF = 32;
char ioBuff[BUFF];
// create socket and flush memory blocks
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
memset(ioBuff, '0', sizeof(ioBuff));
// set socket properties
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); // 0.0.0.0
serv_addr.sin_port = htons(8080);
// Initialize and start the socket
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
listen(listenfd, 10);
while(1)
{
// receive incoming connection
connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
do
{
// read data from client
n = read(connfd, ioBuff, BUFF);
ioBuff[BUFF-1] = (char)NULL; // terminate string
std::cout << n << ": " << ioBuff;
// write data to client
write(connfd, ioBuff, BUFF);
// continue to read and write until '-1' is received
}while((int8_t)ioBuff[0] != -1);
// close connection and repeat
close(connfd);
sleep(1);
}
}
void* memset(void* b, int c, size_t len) {
char* p = (char*)b;
for (size_t i = 0; i != len; ++i) {
p[i] = c;
}
return b;
}
For a full C++ server and client example, see this post on www.thegeekstuff.com.
Back Story
As part of the same project mentioned in my earlier post, GPIO, BeagleBone, and Bash, the next challenge was to communicate with the device over a network. The first choice that came to mind was the secure shell (SSH). I needed to communicate programmatically using my language of choice, C#.
I found SSH.NET and put something simple together. As excited as I may have been for a successful connection, I was now facing some serious LAG! (You know, the same lag everyone notices when playing Super Smash Bros. Brawl world wide?) It is time for alternatives!
C# doesn't exactly have many good SSH libraries out there for some odd reason. One of those weird outcomes of Microsoft. Nevertheless, all is not lost... I could still do this in C++ and then write a wrapper around that in C#. Success! Using libssh, a free open-source C++ library, I am sending SSH commands much more quickly.
(I need to use C# because I have a library written only in C# - no other language. Though I do now have the source code and could port it, this task would prove time consuming considering several hundred lines of code and then would need debugging and testing letter on - maybe better for a future project)
Just about finished here, several friends point out, using SSH for what I'm trying to accomplish is overkill! Since I am not sending commands through the global network but a local one, I should not need these layers of security. Instead, I should construct a simple socket connection. Benefits: I can get an even faster speed-boost, and I can write the socket client in C# while the socket server is all in C++!
With my trial run, as of today (Feb 18, 2014), I am very pleased with the results!
Tuesday, February 18, 2014
Friday, February 14, 2014
GPIO, BeagleBone, and Bash
As the AUVSI competing team electrical engineer at Utah State University, I have been tasked with the effort to turn our skeletal structure into an ROV (Remotely Operated underwater Vehicle) or in other words, an RC Sub. Well, volunteered, as a chance to get my hands messy with a few new electrical component: BeagleBone Black, Wii Classic Controller, and a few 14" VideoRay Thrusters w/Castle Creations ESCs! (If ever you want good experience and to learn new things outside of school, team-up and enter one of several special annual AUVSI competitions!)
Aside from the small story above, here is the real stuff I'd like to share for the benefit of all developers out there...
The task: Make an RC submarine
User input: Wii Classic Controller
RC Feedback: VideoRay Thruster Control
User-RC Linking: Wireless/WiFi
GPIO Pins!
The main challenge I encountered here is sending commands to the beaglebone and getting a pinout reaction from it. Arduino has the 'Serial' libraries but I'm not sure for the beaglebone. (It has been a bit of a challenge to find what I want exactly through Google.) Perhaps there is something, but for now, I found another way: my favorite Linux feature! The Bash/Shell Terminal!
Since Linux is a big fan of files, one doesn't need to go and write drivers to read and write IO data. With that said, one can simply read from or write to a GPIO pin just as they would any other file!
By default, GPIO 'files' have not been created yet and therefore need to be.
This can be done as follows:
# this will create the file for GPIO_30
# (Pin 11 on the P9 header)
echo 30 > /sys/class/gpio/export
Here is a pinout diagram of the BeagleBone Black:
Now to set the bin as an input or an output pin:
echo out > /sys/class/gpio/gpio30/direction # for output
echo in > /sys/class/gpio/gpio30/direction # for input
# NOTE: you can also set the pin to output
# and high or low at the same time by using
# 'high' or 'low' in place of 'out.'
To write to a pin, type the following shell command:
echo 1 > /sys/class/gpio/gpio30/value
# this will set GPIO_30 to high; 0 is for low
To read from a pin, type the following:
cat /sys/class/gpio/gpio30/value
# this will echo the current bit value of the wire
PWM Pins!
I spent a bit of time messing around with general purpose IO pins controlling my BBB with a Wiimote. Again, the overall objective is to control an AUV with the wiimote extensions. (Check out my socket server source code here. Simply use the system("") and a switch to run commands. For the wiimote part, I used a revised version of the wiimotelib library online as well as the C# client socket example from MSDN)
To get started with PWM output, we need to set up the environment:
echo am33xx_pwm > /sys/devices/bone_capemgr.9/slots
Next, to assign a pin: (these lines will assign pins P8_13 and P9_14 respectively)
echo bone_pwm_P8_13 > /sys/devices/bone_capemgr.9/slots
echo bone_pwm_P9_14 > /sys/devices/bone_capemgr.9/slots
Set the period and duty for each pin:
# so 20000000 = 0.02 seconds
echo 20000000 > /sys/devices/ocp.3/pwm_test_P8_13.15/period
# so 10000000 = 0.01 seconds
echo 10000000 > /sys/devices/ocp.3/pwm_test_P8_13.15/duty
echo 20000000 > /sys/devices/ocp.3/pwm_test_P8_14.16/period
echo 10000000 > /sys/devices/ocp.3/pwm_test_P8_14.16/duty
And vuala, two pwm pins both running at 50%.
NOTE:
More Pins!
Sometimes what is available is still not enough! But, no worries; there is a way to acquire about an additional 20 pins - which include additional UARTs and PWMs. To do this, we must disable the auto-loading of the HDMI cape (assuming you will not need a display to work on):
cd /home/debian/Desktop
# cd /home/root/Desktop - for Angstrom distros
mkdir card
mount /dev/mmcblk0p1 card
nano card/uEnv.txt
# uncomment 'optargs=quiet capemgr.disable_partno=BB-BONELT-HDMI,BB-BONELT-HDMIN'
# BE WARNED! If you disable the eMMC as well, you will never be able to access your bone again save it be through an SD card and would need to reinstall Linux otherwise. The eMMC is like your hard drive - you don't need it if and only if you boot from an SD card (like the blue steel bone)
# Save
umount card
rm -rf card
reboot
Happy exploring the Internet of Things!
Aside from the small story above, here is the real stuff I'd like to share for the benefit of all developers out there...
The task: Make an RC submarine
User input: Wii Classic Controller
RC Feedback: VideoRay Thruster Control
User-RC Linking: Wireless/WiFi
GPIO Pins!
The main challenge I encountered here is sending commands to the beaglebone and getting a pinout reaction from it. Arduino has the 'Serial' libraries but I'm not sure for the beaglebone. (It has been a bit of a challenge to find what I want exactly through Google.) Perhaps there is something, but for now, I found another way: my favorite Linux feature! The Bash/Shell Terminal!
Since Linux is a big fan of files, one doesn't need to go and write drivers to read and write IO data. With that said, one can simply read from or write to a GPIO pin just as they would any other file!
By default, GPIO 'files' have not been created yet and therefore need to be.
This can be done as follows:
# this will create the file for GPIO_30
# (Pin 11 on the P9 header)
echo 30 > /sys/class/gpio/export
Here is a pinout diagram of the BeagleBone Black:
Now to set the bin as an input or an output pin:
echo out > /sys/class/gpio/gpio30/direction # for output
echo in > /sys/class/gpio/gpio30/direction # for input
# NOTE: you can also set the pin to output
# and high or low at the same time by using
# 'high' or 'low' in place of 'out.'
To write to a pin, type the following shell command:
echo 1 > /sys/class/gpio/gpio30/value
# this will set GPIO_30 to high; 0 is for low
To read from a pin, type the following:
cat /sys/class/gpio/gpio30/value
# this will echo the current bit value of the wire
PWM Pins!
I spent a bit of time messing around with general purpose IO pins controlling my BBB with a Wiimote. Again, the overall objective is to control an AUV with the wiimote extensions. (Check out my socket server source code here. Simply use the system("") and a switch to run commands. For the wiimote part, I used a revised version of the wiimotelib library online as well as the C# client socket example from MSDN)
To get started with PWM output, we need to set up the environment:
echo am33xx_pwm > /sys/devices/bone_capemgr.9/slots
Next, to assign a pin: (these lines will assign pins P8_13 and P9_14 respectively)
echo bone_pwm_P8_13 > /sys/devices/bone_capemgr.9/slots
echo bone_pwm_P9_14 > /sys/devices/bone_capemgr.9/slots
Set the period and duty for each pin:
# so 20000000 = 0.02 seconds
echo 20000000 > /sys/devices/ocp.3/pwm_test_P8_13.15/period
# so 10000000 = 0.01 seconds
echo 10000000 > /sys/devices/ocp.3/pwm_test_P8_13.15/duty
echo 20000000 > /sys/devices/ocp.3/pwm_test_P8_14.16/period
echo 10000000 > /sys/devices/ocp.3/pwm_test_P8_14.16/duty
And vuala, two pwm pins both running at 50%.
NOTE:
- As the duty cycle increases, an LED will dim, i.e. 10M is brighter than 15M.
- For my device, the path is /sys/devices/ocp.3/*, however another has reported their path to be located at /sys/devices/ocp.2/*. cd to /sys/devices and type 'ls' to list available titles.
More Pins!
Sometimes what is available is still not enough! But, no worries; there is a way to acquire about an additional 20 pins - which include additional UARTs and PWMs. To do this, we must disable the auto-loading of the HDMI cape (assuming you will not need a display to work on):
cd /home/debian/Desktop
# cd /home/root/Desktop - for Angstrom distros
mkdir card
mount /dev/mmcblk0p1 card
nano card/uEnv.txt
# uncomment 'optargs=quiet capemgr.disable_partno=BB-BONELT-HDMI,BB-BONELT-HDMIN'
# BE WARNED! If you disable the eMMC as well, you will never be able to access your bone again save it be through an SD card and would need to reinstall Linux otherwise. The eMMC is like your hard drive - you don't need it if and only if you boot from an SD card (like the blue steel bone)
# Save
umount card
rm -rf card
reboot
Happy exploring the Internet of Things!
Wednesday, February 12, 2014
Vertical MenuStrip in C#
As part of a long term project which requires the creation of many custom controls, I recently encountered a hang-up on one in particular: the menu. At a first glance, all there really needs to be done is to override the various paint methods in an extended version of the ToolStripRenderer class and insert my fancy drawing code. However, the real problem came when I needed to render a menu like a ContextMenuStrip only in a window.
With a bit of quick research and perusing through the libraries, I learned of the Layout feature and how Dock still works even in MenuStrips. By setting Dock to Fill and Layout to VerticleStackWithOverflow, I should get the desired result right. Not so! This was still a menu and menu's do not render hot-keys, images, check-states, or ancestry. I didn't know it yet, but three days later (three days of hacking together something clunky by similar) I realized I could mask the under-the-hood functionality with emulation using the very same custom renderer that makes my menus look pretty.
My end result, a windowed context menu:
Solution:
In the method call to 'OnRenderMenuItemBackground,' make an additional call to OnRenderItemText (for the shortcut display string), OnRenderArrow (only if the item has children), and OnRenderItemCheck (only if the item is marked as checked). You will need to give your own rectangles but that's all part of the fun of rendering!
Some may ask: "What use does this have?"
The answer is simple; Based on developer feedback from professional media industries, when one has over a hundred or so menu items to choose from, the user can get lost real quickly. And even if they knew where things are, it still requires a bit of time to navigate the menu hierarchy before finally selecting the very menu item. If you have ever been involved in a large scale project where deadlines need to be met, you will agree that time is precious. Accessing the menu item may take only a second or two in real time, but this all adds up. So a solution like this is more of a necessary optimization: The user selects the key menu that is accessed often and turns it into a painter's pallet. And when they're done, they simply close the window - the menu will still be available where all other menus are located.
Thursday, January 9, 2014
TX, RX, and UART - The Ethernet Cable
I am tasked with an objective to acquire an internet signal over 500 feet away from the internet source. The owner is hesitant to use Ethernet cabling and is unwilling to go through the trouble of setting up wireless router hopping. The first concept that immediately comes to mind, I waited months to try: Google Fiber. Now, this feature isn't yet available in Alaska, however, I could emulate it! After all, all I would need is a 570 foot fiber reel, a computer, internet, and some way to put everything together... At first glance, this is pretty strait forward, but when I go to look inside of that Ethernet cable, I am baffled. Which wire does what?!
There are a total of eight (8) wires in an Ethernet cable, where there are a total of four pairs. Each pair does it's own thing:
There are a total of eight (8) wires in an Ethernet cable, where there are a total of four pairs. Each pair does it's own thing:
- Wire 1 & 2: Transmit information (otherwise known as the TX line)
- Wire 3 & 6: Receive information (otherwise known as the RX line)
The remaining two pairs (4 & 5 and 7 & 8) vary upon application.
In the first (common) application, the pairs function as follows:
- Wire 4 & 5: Power ( + VAC)
- Wire 7 & 8: Ground ( - GND)
And in the second application, common to servers and other high data communication applications, two pairs will transmit and two will receive:
- Wire 4 & 5: TX (unofficial)
- Wire 7 & 8: RX (unofficial)
Okay, next: why is there a pair for TX and the same for RX. Or in other words, what does TX+ and TX- mean (the same for RX)? The answer is simple: the data that runs through D+ and D- is the same. The only difference is that D- is the exact opposite of D+. (Imagine drawing a graph of D+ and then flipping it upside down - this is what the graph would look like for D-) What use is this? Over long distances, wires can pick up 'noise' just like an antenna to a radio. What is cool about this design is what happens to that noise on the other end. When the data is received on the other end, the graph of D- is flipped over again and then added to D+ essentially canceling out the noise - aka noise cancellation. After all 1 + -1 = 0 and 2 + -2 = 0 as well. See this demonstration below:
Great, we solved for noise, but I still don't know how little bits are sent along this wire... don't you need a clock or something? Yes you do! In fact, you need two and a bit of asynchronization. Welcome the magic of UART (Universal Asynchronous Receiver/Transmitter)! From the transmitting end, the bits are clocked out, but only the bits and not the clock its self. As for the receiving end, it samples the bits with its own clock and then makes sense of the full picture. Take a look at this Wikipedia article for an in depth review of this data handling: https://en.wikipedia.org/wiki/Universal_asynchronous_receiver/transmitter
WOW, that was much simpler than I thought! Well... now that I have been enlightened. And of course, I did have to run through several hours of research and reading, but now I can present it here, all in one comprehensible piece!
Oh, and did I mention that USB works in a similar manner? It's a half duplex instead of a full duplex (which is the Ethernet cable). Also get to know about buffer rings!
Ethernet Speeds:
Cable Type
|
Maximum Data TX Speed
|
Maximum Bandwidth
| |
|---|---|---|---|
Category 3
|
UTP
|
10 Mbps
|
16 MHz
|
Category 5
|
UTP
|
10/100 Mbps
|
100 MHz
|
Category 5 e
|
UTP
|
1000 Mbps
|
100 MHz
|
Category 6
|
UTP or STP
|
1000 Mbps
|
250 MHz
|
Category 6 a
|
STP
|
10,000 Mbps
|
500 MHz
|
Category 7
|
SSTP
|
10,000 Mbps
|
600 MHz
|
To see your computer's bandwidth:
Windows:
Go to Start>Control Panel>Hardware and Sound>Device Manager
Look for your Network Device(s) under Network Adapters
Right-click on the device and select Properties
Select the tab titled Link Speed
Under Speed and Duplex, you can see a selection listing all speeds for that particular device.
Linux:
Go to a Terminal and type:
lspci | grep Ethernet
# or sudo lshw
When you find the name of the port, type: ethtool name_of_port # ex: ethtool eth0
Under Supported link modes you'll see all speeds for that particular device.
I have a 10-year-old HP Compaq that supports 1000baseT/Full or in other words, 1Gb/sec.
I also have the same for an HP Z1 (1.0 Gbps Full Duplex).
Windows:
Go to Start>Control Panel>Hardware and Sound>Device Manager
Look for your Network Device(s) under Network Adapters
Right-click on the device and select Properties
Select the tab titled Link Speed
Under Speed and Duplex, you can see a selection listing all speeds for that particular device.
Linux:
Go to a Terminal and type:
lspci | grep Ethernet
# or sudo lshw
When you find the name of the port, type: ethtool name_of_port # ex: ethtool eth0
Under Supported link modes you'll see all speeds for that particular device.
I have a 10-year-old HP Compaq that supports 1000baseT/Full or in other words, 1Gb/sec.
I also have the same for an HP Z1 (1.0 Gbps Full Duplex).
Saturday, December 28, 2013
The Usefullness of Linux
One thing every Linux user should familiarize themselves with at some point in time is the terminal. Bash scripting is not too different from any other scripting language in my opinion. Once you get familiar with bash, all of a sudden you may indeed realize the power and flexibility behind Linux. Note: if you try this in Windows' command line, it is possible... but... good luck figuring it out - it's a mess!
Here I wish to share the commands I find useful, and may periodically update this post as I discover new commands... Any combination of commands can be saved in a bash file (your_file.sh); Remember to include #! /bin/bash at the beginning of the file.
Here I wish to share the commands I find useful, and may periodically update this post as I discover new commands... Any combination of commands can be saved in a bash file (your_file.sh); Remember to include #! /bin/bash at the beginning of the file.
- Install an app or library: sudo apt-get install app-name-here
- Uninstall an app or library: sudo apt-get remove app-name-here
- Update all apps and libraries: sudo apt-get update
- Wireless Fix:
rfkill unblock all
rfkill list all - Operating System Version: cat /etc/lsb-release
- VirtualBox Shared Folders: (Note: 'shared_folder_name' is created by clicking on 'Shared folders' in the VirtualBox Manager and then by clicking add folder icon)
cd ~
cd /media
sudo mkdir folder_name_here
sudo mount -t vboxsf shared_folder_name /media/folder_name_here - List items in folder: ls
- Navigate directories:
# navigate forward
cd /folder/path
# navigate backwords
cd ../.. - Kill process: sudo killall program_name_here
- Current username: whoami
- IP and Network information: ifconfig
- Network Ports: iwconfig and ip addr show
- Port-scan a computer/address (requires nmap): nmap -sS -O computer_ip_address
- Edit file: gksudo gedit /path/to/file.txt OR sudo nano /path/to/file.txt
- Get list of installed applications: dpkg --get-selections
- Start app (server-side SSH - WARNING: See below!): DISPLAY=:0.0 application_name
- Send virtual file input to app upon execution:
app_name << EOF
your file content here
EOF - Evaluate a console command incompatible to bash syntax:
# wmctrl is a non-native bash command and sublime is an active text editor
# see programming bellow for more bash syntax
function func{
eval "wmctrl -a sublime"
} - Gain root-level access: sudo su root
- Get running time: uptime
- Take a screenshot (prt sc - requires gnome-screenshot):
gnome-screenshot -f /home/user/Desktop/pic.png - Copy file: cp /path/to/file.txt /path/to/newfile.txt
- Move file: mv /path/to/file.txt /new/path/to/file.txt
- Open port in firewall: sudo ufw allow 1500
- Close port in firewall: sudo ufw deny 1500
- Mount device to folder: sudo mount /path/to/source /path/to/folder
- List connected USB devices: lsusb
- Port Forwarding:
echo 1 > /proc/sys/net/ipv4/ip_forward
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT - Run app or process in background: google-chrome "http://www.blogger.com/" &
- Search path for a program file: which $program_name
- Hibernation or Sleep: sudo pm-suspend
- Manual for a command: man command
- View and Manage Ethernet Media:
man ethtool
man mii-tool - System processes and monitoring top # htop
- Send messages to users on remote server: w; write 'user' |pts\$n|;
- Set static IP:
nano /etc/network/interfaces
# enter the following
auto eth0 # set on startup
iface eth0 inet static # dhcp for temporary IP
address 10.0.0.25 # the static IP
netmask 255.255.255.0
network 10.0.0.0 # IP for 10.0.0.X networks
broadcast 10.0.0.255
gateway 10.0.0.1 # default IP of device - similar to the IP used to access router config - Set temporary IP (good for tapping into a routerless network; aka: a network where IPs are not assigned by any DNS or other address manager):
ifconfig eth0 down
ifconfig eth0 X.X.X.X up # replace 'X' with custom IP
Setup SSH (Linux to Linux):
- sudo apt-get install ssh # on both systems
- sudo apt-get install openssh-client # on the accessing system
- gksudo gedit /etc/ssh/sshd-config # on the accessed system
- Type a port number of choice. For example: Port 1500 or Port 4321. Save.
- Make sure only one ssh process is running to avoid a mess. Check with ps -e | grep ssh If more than one are running, kill the process (sudo killall sshd) or if none are running, start one up with sudo /etc/init.d/ssh start. (For some installations, first type eval "sudo $(which sshd)" because sshd may be located in another directory such as /usr/sbin/sshd .)
- From the accessing computer's terminal, establish a connection with ssh -p port username@ipaddress for example: ssh -p 1500 admin@128.0.4.12
- For added security, install and run Firestarter on the accessed computer. Under 'Policy,' add a rule to allowed services. Include ssh port number and IP of accessing computer.
- To exit the session, press Ctrl+D.
- Copy a file from server to client:
SCP -P 1500 admin@128.0.4.12:/path/to/file.txt /path/copied/to - Copy a file from client to server:
SCP -P 1500 /path/to/file.txt admin@128.0.4.12:/path/copied/to - Copy folder & files from server:
SCP -P 1500 -r admin@128.0.4.12:/server/folder /path/copied/to - Copy folder & files to server:
SCP -P 1500 -r /client/folder admin@128.0.4.12:/path/copied/to
Running Applications Server-Side:
If an app were to run from the console, console access will not be returned until the app closes. So, if an app were run through an SSH terminal, either another SSH connection will need to be made to close the program or someone server-side would need to close the app. However, there is a work-around: start a new console server-side and from that console, start the application. Here is a demo (Mint to Kubuntu tested - requires xdotool):
DISPLAY=:0.0 konsole
DISPLAY=:0.0 xdotool type "google-chrome-stable"
# enter: KP_Enter; space: space; backspace: BackSpace
# Run application:
DISPLAY=:0.0 xdotool key KP_Enter
Bash User Interface:
Sometimes it can be convenient to add a user interface for a user's comfort and to reduce confusion. Zenity does just this. But of course, one can take Zenity another step forward with YAD - as the developers know it as: "Zenity on Steroids." All the features of Zenity and then some. Here is a demo (requires YAD):
frmdata=$(yad --title "Test Form" --form --field "Address" --field "name")
frmaddr=$(echo $frmdata | awk 'BEGIN {FS="|"} { print $1 }')
frmname=$(echo $frmdata | awk 'BEGIN {FS="|"} { print $2 }')
echo $frmaddr
echo $frmname
Bash User Interface:
Sometimes it can be convenient to add a user interface for a user's comfort and to reduce confusion. Zenity does just this. But of course, one can take Zenity another step forward with YAD - as the developers know it as: "Zenity on Steroids." All the features of Zenity and then some. Here is a demo (requires YAD):
frmdata=$(yad --title "Test Form" --form --field "Address" --field "name")
frmaddr=$(echo $frmdata | awk 'BEGIN {FS="|"} { print $1 }')
frmname=$(echo $frmdata | awk 'BEGIN {FS="|"} { print $2 }')
echo $frmaddr
echo $frmname
Basic Bash Programming:
| # variables
str="hello world"
var=2 # write to a file echo "hello" > file.txt # read from a file while IFS= read -r line; do echo $line done < file.txt
# create a folder
mkdir folder_name
echo "hello world"
# read from console read var
# conditioning
if ["true" = "true"]; then
echo "this is true"
elif ["a" == "b"]; then echo "maybe not"
else
echo "No!"
fi
|
# comment line
# foreach loop
for i in $( ls ); do
echo item: $i done # for loop for i in `seq 1 10`; do echo $i done for ((i=0; i<10; i++)); do echo yes done # while loop CTR=0 while [ $CTR -lt 10 ]; do echo The counter is $CTR let CTR=CTR+1 done # until loop CTR=0 while [ $CTR -lt 10 ]; do echo The counter is $CTR let CTR=CTR+1 done | # functions function func { # echo params echo $1 $2 $3 } func hello world ! # menu prompt OPTIONS="Hello Qt" select opt in $OPTIONS; do if ["$opt" = "Qt"]; then echo done exit fi done # a static class could # be seen as a bash file # regex ( ~ ) [[ "Hello World" =~ "Hello"$ ]] && echo matched # evaluation eval "expression" # delete file or directory rm -r /path/to/file.txt |
Remotely access Linux computer via SSH:
http://www.linuxloop.com/2009/09/28/remotely-accessing-your-linux-computer-part-1/
http://www.linuxloop.com/2009/09/28/remotely-accessing-your-linux-computer-part-1/
More about xdotool virtual input:
http://www.semicomplete.com/projects/xdotool/xdotool.xhtml
Some Bash One-Liners:
http://www.catonmat.net/blog/bash-one-liners-explained-part-one/
http://www.semicomplete.com/projects/xdotool/xdotool.xhtml
Some Bash One-Liners:
http://www.catonmat.net/blog/bash-one-liners-explained-part-one/
Featuring YAD - Install and Program:
http://www.webupd8.org/2010/12/yad-zenity-on-steroids-display.html
Ubuntu Firewall Commands:
https://help.ubuntu.com/12.10/serverguide/firewall.html
Networking:
https://wiki.debian.org/BridgeNetworkConnections
https://help.ubuntu.com/12.10/serverguide/firewall.html
Networking:
https://wiki.debian.org/BridgeNetworkConnections
Date, Time, and TimeBombs:
http://tldp.org/LDP/abs/html/timedate.html
More Linux Commands:
http://ss64.com/bash/
http://community.linuxmint.com/tutorial/view/244 [broken]
Custom Text:
http://misc.flogisoft.com/bash/tip_colors_and_formatting
http://tldp.org/LDP/abs/html/timedate.html
More Linux Commands:
http://ss64.com/bash/
http://community.linuxmint.com/tutorial/view/244 [broken]
Custom Text:
http://misc.flogisoft.com/bash/tip_colors_and_formatting
[My Simple Back Story]
It has been close to two years now of getting use to the ways of Linux - a free and secure operating system. Depending on the title and version of Linux, one may face varying levels of difficulty. Linux does have a stereotype of being 'challenging' and 'only used by computer experts.' How do I know this? Because I was once one of those to hear them; even further, I saw one of the first Linux operating systems in action and immediately agreed about it's difficulty (even though I never even touched it once).
I gave it a try one day just to see - perhaps about four years ago this was. Kubuntu, my first choice, simply because it was blue. I realized that, although a little different from Windows and OSX, it actually had a very familiar feel to it. A 'start' button in the lower left, the time, network, and other tasks in the lower right, windows showed up in the task bar and have the usual minimize/maximize/close buttons at the top... Browsing the internet is just as easy. With Sublime Text, I have an advanced version of notepad. With OpenOffice or LibreOffice, I have free and compatible version of MSOffice. With Wine (a windows emulator) I can run windows-based applications such as windows notepad.
Later, my roommate in college, introduced me to Linux Mint. Just like Kubuntu, Mint is a child branch of the Ubuntu based systems. Linux Mint is probably the easiest title out there to date. I've been using it for the past three days and all I can say is 'Wow, where have you been all my life?!'
Here is a little something interesting I thought of: if you can master Linux Mint, you will be able to handle both Windows and Mac. Also, as a result of persuading some friends to convert from Mac to Linux, I learned of a project called Macbuntu which is OSX functionality with Linux as the underlying engine.
All this is some pretty cool stuff. I was convinced the moment I learned of the simplicity. This operating system is for the naive all the way to the expert. And remember, you've already had a taste of Linux if you've ever surfed the web!
Wednesday, November 20, 2013
Writing a File to Computer with Arduino
As far as I found, there is no native support for this in the Arduino libraries. Nevertheless, it can be done and with any language of choice! For my demonstration I will use C#. Now so I don't confuse my audience already, writing requires two separate applications, one for the Arduino board and one for the computer - the app for Arduino is in C/C++ while the app for the computer is in C# (or any supported language of your choosing really).
To get started, lets look at the code for the Arduino:
For every 500 milliseconds, the board will send the message "Hello World!" via USB to the computer. Any program listening on that port, will hear the message. (I added a little extra code that toggles an on-board LED on and off after every consecutive message sent - just to signify it itself is functioning properly.)
Serial.begin() primes the USB for data transfer and the (9600) portion is the baud rate (pulses per second - the ancestor of bits per second).
Serial.end() ends the transmission and releases control of the port.
Serial.println() writes ASCII data to the port.
A list of Serial functions can be found on Arduino.cc under References: http://arduino.cc/en/Reference/Serial
Now on to the computer side of things:
First, create a SerialPort object and give it a name: 'COM', the same baud rate set for the Arduino board (9600), and finally, no parity checking. (A parity bit is a simple way of error checking data received; more on parity checking can be found here) Purposefully, I set the timeout to be the same as my first app so to be almost perfectly synchronous.
Open the port and start the Read thread. The read thread is a separate thread that will indefinitely listen for any and all incoming messages on the port and then print them to the console.
So where is the code to write a file? Well, by now you would know enough to take it from here, but if you really need to know how to write a file in C#, here is a simple one-liner hack:
More file handling example can be found here: microsoft OR stackoverflow
Feel free to ask questions!
To get started, lets look at the code for the Arduino:
int led = 13;
bool flag = true;
void setup()
{
pinMode(9, OUTPUT);
}
void loop()
{
Serial.begin(9600);
Serial.println("Hello World!");
Serial.end();
Toggle();
delay(500);
}
void Toggle(){
if(flag) digitalWrite(led, HIGH);
else digitalWrite(led, LOW);
flag = !flag;
}
For every 500 milliseconds, the board will send the message "Hello World!" via USB to the computer. Any program listening on that port, will hear the message. (I added a little extra code that toggles an on-board LED on and off after every consecutive message sent - just to signify it itself is functioning properly.)
Serial.begin() primes the USB for data transfer and the (9600) portion is the baud rate (pulses per second - the ancestor of bits per second).
Serial.end() ends the transmission and releases control of the port.
Serial.println() writes ASCII data to the port.
A list of Serial functions can be found on Arduino.cc under References: http://arduino.cc/en/Reference/Serial
Now on to the computer side of things:
using System;
using System.IO.Ports;
using System.Threading;
namespace Arduino_SerialReader
{
class Program
{
static SerialPort port;
static void Main(string[] args)
{
port = new SerialPort("COM", 9600, Parity.None);
Thread reader = new Thread(Read);
port.ReadTimeout = 500;
port.Open();
reader.Start();
}
static void Read()
{
bool flag = true;
while (flag)
{
try
{
string message = port.ReadLine();
Console.WriteLine(message);
}
catch { }
}
}
}
}
First, create a SerialPort object and give it a name: 'COM', the same baud rate set for the Arduino board (9600), and finally, no parity checking. (A parity bit is a simple way of error checking data received; more on parity checking can be found here) Purposefully, I set the timeout to be the same as my first app so to be almost perfectly synchronous.
Open the port and start the Read thread. The read thread is a separate thread that will indefinitely listen for any and all incoming messages on the port and then print them to the console.
So where is the code to write a file? Well, by now you would know enough to take it from here, but if you really need to know how to write a file in C#, here is a simple one-liner hack:
File.WriteAllText("filename.txt", "your string here");
More file handling example can be found here: microsoft OR stackoverflow
Feel free to ask questions!
Friday, October 4, 2013
How to Become a Millionaire
For those who want to know the secret(s) to how to become a millionaire, you must be willing to accept what is required of you, and do it in faith that these secrets are tried and true and will not fail you.
START EARLY
PAY YOURSELF FIRST
&
MAKE IT AUTOMATIC
Now, is that really such a challenge? Well, for many it is, because they lack faith in the system. Only when they are shown the underlying logic that makes this system work, are they more willing to try it - yet, even then, after witnessing hard core evidence, they may still shy away simply because of a lack of trust (perhaps not as much but nonetheless). If you are one of those who need to see how this really works before you put your money on the line, and to make sure I am not just pulling your leg, or you simply just want to know more about this in general, then I recommend a book for you called,
"The Automatic Millionaire: A Powerful One-Step Plan To Live And Finish Rich"
by David Back
All of about $7 to $10 for a new copy (or as low as $4 used). I purchased a used copy my self for a University Family Finance class I recently had taken. It was an EZ-A class that would satisfy a general education graduation requirement. I figured "why not?", it would be more fun than a second history or humanities class and guess what, I do fancy some business and number-crunching from time to time.
I graduated highschool one year after they started requiring students to take a financial literacy class. I learned quite a bit in that time and it really motivated me to take action and build up my wealth - again, not a very challenging class. I even desired to dive into stock exchange after hearing the many success stories from older generations, then, around my age.
My first goal with taking a similar class was just to slap another beautiful 'A' on my transcript. Then, as the week drew closer to this class, I started thinking about how this class would benefit me beyond an A-grade. The thoughts that ran through my mind got me even more excited and I couldn't wait for class to begin, like the night before Christmas.
One of the books that where required on my list was the book 'Automatic Millionaire.' Those words sounded like the book was going to be an entertaining read - and I am not one who likes to read just any book that is required of me. Anyways, the week came when we needed to read the entirety of the book and write a summary about it. I must say, the introduction really builds on one's curiosity to 'know this answer' of which they so highly esteem. David shares a simple proof of concept through a story of how he came to learn about this secret. Following his story, David dedicates the remaining chapters to a deeper understanding of how things work and what one needs to do to become a success. (He also includes a checklist at the end of each chapter because 'there is just something about righting it down that motivates one to act upon it')
Buy the book, read it, live it, and love it!
Just a Little Note: This book (The Automatic Millionaire) is NOT about becoming an instant millionaire, but rather about how to retire as a millionaire without all the hullabaloo one could think of. Some of these techniques mentioned in the book also work outside the bounds of retirement as well.
Subscribe to:
Posts (Atom)


