Android Wear and the Asus ZenWatch 3

Asus Zenwatch 3 Illusion Watchface

Connected sports watches are poor smartwatches

I’ve been waiting for a good opportunity to get a smartwatch for a pretty long time now. As years went by, I got increasingly tired of missing calls and messages just because I didn’t hear or feel my phone ringing/buzzing in my pocket or bag. Having a device on my wrist notifying me of such events seemed to be the prefect solution. Last year I bought the Polar M400 mainly for running and tracking workouts, but also for its smart notifications feature. It’s an excellent, rugged sports watch and activity tracker, but it does very poorly in the notifications department. The Polar app for Android is very nice and it’s very convenient to go for a run with the watch only and check out the stats on your phone afterwards. However, it’s too bulky for a normal everyday watch and my biggest gripe is, that it lacks vibration. It can only beep, which is a no-go for me. I thought it’d be enough to look at the watch every now and then to check notifications, but I kept missing my wife’s calls and other important stuff. After researching the internet for Garmin, Suunto and other Polar products, I came to the conclusion, that sports watches and fitness trackers cannot fill the role of a real smartwatch, at least not yet. The only exception seemed to be the Pebble Time 2, which I eventually planned to buy. It was a real smartwatch with great looks, a heart rate monitor and unmatched battery life, but it was gone when Pebble went broke. I also considered the Samsung Gear S line and the Ticwatch 2, but I didn’t want to buy into those ecosystems. I especially disliked Samsung’s version of Android and the idea of Tizen, yet another wearable OS. As a hard-core Android user, my only viable option was Android Wear.

Searching for the “perfect” smartwatch

The next challenge was finding a good Android watch under 250 Euros. I didn’t want to spend more money on one more gadget that was destined to become obsolete and abandoned by its manufacturer in only 2 years. I already had my 500-Euro Nexus 5X for that (officially it was € 530 in Austria)! I looked at the 2nd gen Moto 360, but I didn’t like the flat tire and the idea of an LCD screen on a smartwatch. I wanted something with an AMOLED screen, ambient light sensor, mic, speaker and circular design that looked like a real watch. The Fossil Q Founder and Marshal had the best looks, but the technology inside was too weak for 250 Euros. They had LCD screens with flat tire and I read conflicting reports on them having an ambient light sensor or not. The Huawei watch was really beautiful, but it was still around € 300 and lacked a light sensor. The LG Urbane was nice, but lacked both a speaker and a light sensor. GPS and optical heart rate monitor wasn’t important for me at all, because I wouldn’t have used a good looking smartwatch for sport and fitness anyways. My Polar was designed just for that!

I eagerly waited for the release of LG’s new “Nexus” watches with Android Wear 2. I wanted to buy the smaller one, but I was really disappointed by both. The Style’s specifications don’t justify its $ 250 price tag at all. It lacks a speaker and I find its design very boring. The Sport looks way too big, has 4G LTE, which I don’t need and costs 350 bucks. I really don’t get who on earth needs a cellular connection in a watch. Most people carry their phones with them everywhere anyways. 4G LTE is just an unnecessary battery hog and makes the device bulky. I certainly don’t need it my watch!

The ZenWatch 3 – cut down on your crap Asus!

It all came down to the Asus ZenWatch 3, which is the best value for money right now. For only € 230, it has amazing features and specs:

  • beautiful, elegant, circular design
  • sleek, all metal body with a silicone strap (genuine leather is also available)
  • gorgeous AMOLED touchscreen
  • ambient light sensor, without a flat tire!
  • Wifi and Bluetooth
  • microphone and speaker
  • 2 costumizable buttons
  • waterproofness
  • Snapdagon 2100 processor specially designed for wearables
  • upgrade to Android Wear 2
  • extremely fast charging – for me about 30 mins to full charge
  • solid, all day battery life with always on screen

After using the watch for two weeks, I have to say I like it. Vibration could be stronger, but it’s hard to miss a call now. Missing messages can still happen, because the watch vibrates just once and it does so very shortly. By installing ZenWatch Manager you get a lot of beautiful watch faces. I like the fact that I can change my watch face any time I like, for anything I like. Battery life is good: I usually start with full charge at 7 am and I still have around 30% left at 10 pm, WITH always on screen. The ability of taking phone calls is also very useful, because I don’t have to run for my phone every time. For example, when my wife calls me while I’m changing diapers for our baby, I can just pick it up right on the watch. It’s very practical, but there’s a bug. Since Android 6 I think, your phone switches to do not disturb (DND) mode during phone calls. If I accept a call on the watch, it won’t automatically get out of DND mode after the call, but I have to manually disable it each time. I don’t know if it’s Asus’ or Android Wear’s fault, but it’s very annoying! Tehre’s one serious problem for which only Asus is to blame: if you activate Asus Zenfit on the watch (by granting it permissions), it drains the battery abnormally fast! That’s why I use Google Fit for activity tracking and it has no such negative impact on the watch’s battery life. This is really bad of Asus and it keeps alive Android’s most disturbing problem as a platform: manufacturers forcing their own crap down the throats of Android users, without even optimizing their own apps for their own products! No wonder Apple is so successful that Google is trying to copy them by launching Pixel devices. OEMs should really cut down on their crappy Google duplicate apps or at least let the users decide if they want them on the product they payed for or not.

Android Wear – the apps make the difference

Speaking of Android Wear itself, I like it too. It’s great for notifications, for dealing with phone calls, messages, emails, for basic activity tracking and music control. The main advantage here is the apps. More and more Android apps are enhanced for Wear, adding more and more functionality to your watch. Of course many Google apps are available for Wear and there’s Skype, OneNote, Spotify, just to mention a few of my favorite ones too. If you use 2-step verification, having Google Authenticator on your wrist is very convenient. If you’re not into Apple and the apps are your thing, your only viable option is Android Wear. The Samsung Gear S3 looks awesome, but I don’t think app developers would embrace it as the 3rd wearable platform. They’ve even been ignoring Microsoft’s mobile platform for years, let alone Blackberry, Firefox OS or the Ubuntu phone. It seems the world has room only for 2 mainstream platforms: it’s Apple and Google in mobile and Apple and Microsoft in the laptop/desktop business.

Spotify on the ZenWatch 3
Asus Zenwatch 3 Spotify

Thoughts on the Apple Watch 2 – lack of choice

If you’ve got Apple gadgets, I’m sure your best bet is on the Apple Watch. Although Apple’s platform is free form fragmentation, it also provides much less choice. If you want a round watch, you’re out of luck. Battery life is supposed to be 3 days, but I’ve read conflicting reports, some saying it doesn’t even make it through one single day. Apps should be no problem though. One ridiculous omission is the always on screen. Why do they take even the choice away? This attitude is the main reason I dislike Apple. You pay a crap ton of money for their product and then you’re pretty much limited to what Apple thinks you should like or how you should use your own device. I used to have an iPad 3 and I had enough of Apple’s treating me like an idiot.

Advertisements
Tagged with: ,
Posted in Reviews

Programming the Arduino with Atmel Studio

Arduino is easy and simple, but comes with limitations

In my previous post I described why I choose Arduino as the platform for my thesis in electrical engineering. The Arduino is a great introduction to electronics, but there’s a lot more to microcontroller programming. The Arduino IDE and its whole hardware and software ecosystem makes it very easy to accomplish complicated things, without understanding how the underlying technology actually works. It gives you the confidence to take off, but if you really want to get into microcontroller programming, you have to go deeper. Most Arduino boards use an Atmel AVR chip, for example the heart of the Arduino Mega is an ATmega2560. You might think, that programming the Arduino is the same thing as programming the chip, but it isn’t. When you’re programming the Mega using the Arduino software, you’re using code that only works inside the Arduino ecosystem. If you take the chip out of the board and try to use it in a different application, your Arduino programming skills become worthless. Programming the chip itself in C requires a lot more knowledge and practice, but you’re not limited to code written by other people. You can embed the chip in any custom application and literally control every bit to do exactly what you want.

Programming the ATmega chip

Atmel AVR chips can be programmed in C with Atmel Studio, which uses the Microsoft Visual Studio shell. It provides a very comfortable way of manipulating control registers, IO-pins and everything else. With the help of this IDE and the datasheet of the given ATmega chip, you can really program anything the controller is capable of: set up SPI, I2C, USART, ADC (Analog Digital Converter) and so on. You just need an ISP USB programmer to connect the chip with your PC. But, there’s an easier way!

Why use an Arduino board after all?

Having an ATmega chip on an Arduino board has some major advantages. First of all, you don’t have to use the Arduino software for programming. You just have to connect the board to your PC via USB, set up Atmel Studio and you’re good to go. Secondly, you have very easy access to all of the different IO, communication and power pins. This is what makes Arduino so great for prototyping.

Setting up Atmel Studio for Arduino

I’ve got the Arduino Mega, which uses the ATmega2560 chip. To set it up in Atmel Studio, you first have to add your chip under “Tools”, “External Tools”. You have to look which COM port your board is plugged into in Device Manager. Next, in “Extenrnal Tools”, you have to add your board, using the following configuration (the Arduino software has to be installed for this to work). Obviously, you have to pick the right COM port:

Device Manager Arduino

Title: a name, like Arduino Mega 2560
Command: C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avrdude.exe
Arguments: -C"C:\Program Files (x86)\Arduino\hardware\tools\avr\etc\avrdude.conf" -patmega2560 -cwiring -P\\.\COM3 -b115200 -D -Uflash:w:"$(ProjectDir)Debug\$(TargetName).hex":i

Atmel Studio External Tools

When creating a new project, you have to choose “GCC C Executable Project” and pick the right chip in the next steps. For me, it’s the ATmega2560. When you’ve written some code, you have to first compile it and then you can load it onto the chip by clicking the name you gave to the board under “Tools”. It’s that easy!

Your best friends are the datasheet and Google

Writing my thesis involves a lot of coding in Atmel Studio. We’re building a system with one master and 24 slave microcontrollers to measure the voltage and temperature of each battery cell in an electric go-kart. Not only ADC has to be properly configured for the slaves, but they have to send all the data to the master using a reliable means of communication. We could use SPI or maybe I2C for this purpose, but we chose USART for a number of reasons – which I’ll explain later. Until recently, I had no idea how to program ADC or USART – or especially how USART worked -, but I was able to figure it out from the datasheet of the chip and by googling and watching YouTube. In the coming blog posts, I’ll show how to set up ADC and USART for the ATmega chips, since they all have to be programmed in pretty much the same way. Keep tuned!

Tagged with: , , , ,
Posted in uC Programming

Displaying Voltage on LCD with Arduino

volt_lcd

Measuring the voltage of a single Li-Ion cell is the basis of any battery management system (BMS), like the one we’re designing for the school’s electric go-kart. This being our thesis – we are a team of three students of Electrical Engineering in our final year – sets some conditions on the design an implementation process. Obviously, we have to build a system, which reliably does what it has to do:

  • control the charging an balancing process (monitor voltage, current, temperature)
  • protect the battery form damage (over-charge and over-discharge)
  • calculate capacity and assess battery health
  • control an LCD display on the vehicle
  • communicate with a C# program

The first condition is time-efficiency. Since it’s an evening school, most of us have a job and some of us a family too. In our free time – I mean what remains after work, attending lectures and family -, we not only have to work on our thesis, but we also have to study for all the tests and exams throughout these final two semesters. We have to use our time well, doing the most in the least amount of time.

The second condition is a consequence of the first one: we have to find the simplest possible way to achieve what we want. There are a lot of cool, smart and advanced solutions possible with today’s technology. The problem is, that building or even just implementing them would be very time consuming. One good example is balancing. We’d love to build a nice, modern active-balancing system with flyback-converters and everything, but understanding and building such a system would take too much time for us. A passive-balancing system is not as advanced, yet gets the job done just as well and it can be built much more easily.

All of these reasons make the Arduino a perfect candidate. There are a lot of additional hardware (shields), libraries and tutorials available for this platform, making it relatively easy to build almost anything, BMS included.

So lets see, how the first step, which is measuring voltage, can be done. I go a little further than that and output the results on a 16×2 LCD display. Wiring the LCD is pretty easy, I won’t go into the details. Just watch this video, that’s how I did it.

I’m using the Arduino Mega 2560 form Sunfounder, becuase it’s got the most analog inputs and costs only about 18 € on Amazon. All the other stuff, including the LCD, came with a Raspberry Pi 2 kit I bought earlier. I just hooked up the LCD and a 50 kOhm poti to control the contrast and displayed the voltage of a 18650 Li-Ion battery (ignore the LED and the resistor on the right side, they just sit there in case I need them for something).

The only trick in the code is getting the voltage right. The battery is connected to one of the analog inputs and the voltage is converted to an integer from 0 to 1023 by the Arduino’s analog digital converter (ADC). This means, that the ADC’s resolution is 1024. It can measure voltage form 0 to 5 Volts in 1024 steps. So if you want to know the voltage, you have to convert the ADC’s output from the number it spits out to a number you can understand. You can do it by dividing this number by 204.8, which you get from dividing the resolution by the range: 1024 / 5. I just rounded it to 205 in the code, which you can see below:

#include <LiquidCrystal.h> // the LCD library

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // initiate pins
float volt;
int sensePin = 0; // analog input 0 is where the positive pole of battery is connected. The negative is connected to ground.

void setup() {
  analogReference(DEFAULT); // default reference is 5 V
  lcd.begin(16, 2); // set the size of the display
}

void loop() {
  volt = analogRead(sensePin) / 205.0; // reading and calculating voltage
  lcd.setCursor(0, 0); // set the cursor to the 1st row, 1st character
  lcd.print("Spannung: ");
  lcd.setCursor(0, 1); // set the cursor to the 2nd row, 1st character
  lcd.print(volt);
  lcd.print(" V");
  delay(500); // do the whole thing over in every half second
}

It’s amazing how easy it is to measure something and display it on an LCD with the Arduino. Just wire it up, include the library, write the code and you’re done. Need to measure more, than 5 Volts? You can do it with a voltage divider. Want to measure current up to 30 A? No problem with a Hall effect sensor like the ACS712. There’s a great video about it too. Then, you can do almost anything by programming your logic and controlling all those inputs and outputs!

Tagged with: ,
Posted in Arduino

Low-Level GPIO Programming of Raspberry Pi 2 in C

The most interesting thing about the Raspberry Pi is programming it’s pins to do something practically useful. As a student of electrical engineering, I’m going to write my thesis in the coming two final semesters about battery cell balancing. To accomplish this, I’ll have to use a microcontroller as the brains of the circuit. The Arduino is a perfect candidate for the task, since it has analog inputs, whereas the Raspberry Pi is only digital. However, the Raspi is capable of more powerful things and it can also take analog input when connected with an Arduino, for example. So I bought my Raspberry Pi 2 back when it was the newest. I bought a case, a 32 GB micro SD card, a wifi dongle, a Sunfounder starter’s kit and installed Raspbian on it. As my code editor I use Geany, which is an awesome little piece of software. The reason for using it is, that I don’t want to write gcc x.c -o x and the rest each time I want to run a program. With Geany, I can build and run code very easily. In the beginning, I used the WiringPi library, which comes with all the functions to play around with GPIOs. And exactly this was the problem. I wanted to understand how those functions worked, how they set a pin high and low, as input and output and so on. I wanted to directly access the pins and write my own functions to control them to make an LED blink, to start with. Using someone else’s code without even understanding it just wasn’t enough for me. I wanted to do real, hard-core microcontroller programming.

It wasn’t easy to find out how to do that, because mostly everyone in the internet was doing high-level programming. Finally I found a blog post from Pieter-Jan here. As it turns out, directly programming the pins is actually easy: you need to access different registers and set specific bits. The meat of the whole thing is finding the registers and set the bits with bit shifting and bitwise operations. In principle it’s very easy, but I couldn’t have done it without Pieter’s blog post and this source. Pieter-Jan’s post is particularly useful, because he actually explains how his code works. Since I mostly copied his code, I won’t explain much here. Ho does a great job doing that on his own website!

The code in both of these sources was written for the first Raspberry Pi, but it works on the Pi 2 as well with only a small modification. BCM2708_PERI_BASE has to be changed to 0x3F000000 and fcntl.h needs to be included in the header file. After (mostly) understanding Pieter’s code, I copied it into a header file and amended it with some of my own functions. Since the Pi 2 has a BCM2836 chip, I named the struct bcm2836_peripheral instead of bcm2835, which is in the first Pi. It is important to note, that this code uses the Broadcomm GPIO numbering, which is different from the WiringPi numbering! If you want to know which pins are what, just type gpio readall in the terminal and you should see this (WiringPi has to be installed):

 +-----+-----+---------+------+---+---Pi 2---+---+------+---------+-----+-----+
 | BCM | wPi |   Name  | Mode | V | Physical | V | Mode | Name    | wPi | BCM |
 +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+
 |     |     |    3.3v |      |   |  1 || 2  |   |      | 5v      |     |     |
 |   2 |   8 |   SDA.1 |   IN | 1 |  3 || 4  |   |      | 5V      |     |     |
 |   3 |   9 |   SCL.1 |   IN | 1 |  5 || 6  |   |      | 0v      |     |     |
 |   4 |   7 | GPIO. 7 |  OUT | 1 |  7 || 8  | 1 | ALT0 | TxD     | 15  | 14  |
 |     |     |      0v |      |   |  9 || 10 | 1 | ALT0 | RxD     | 16  | 15  |
 |  17 |   0 | GPIO. 0 |   IN | 0 | 11 || 12 | 0 | IN   | GPIO. 1 | 1   | 18  |
 |  27 |   2 | GPIO. 2 |   IN | 0 | 13 || 14 |   |      | 0v      |     |     |
 |  22 |   3 | GPIO. 3 |   IN | 0 | 15 || 16 | 0 | IN   | GPIO. 4 | 4   | 23  |
 |     |     |    3.3v |      |   | 17 || 18 | 0 | IN   | GPIO. 5 | 5   | 24  |
 |  10 |  12 |    MOSI |   IN | 0 | 19 || 20 |   |      | 0v      |     |     |
 |   9 |  13 |    MISO |   IN | 0 | 21 || 22 | 0 | IN   | GPIO. 6 | 6   | 25  |
 |  11 |  14 |    SCLK |   IN | 0 | 23 || 24 | 1 | IN   | CE0     | 10  | 8   |
 |     |     |      0v |      |   | 25 || 26 | 1 | OUT  | CE1     | 11  | 7   |
 |   0 |  30 |   SDA.0 |   IN | 1 | 27 || 28 | 1 | IN   | SCL.0   | 31  | 1   |
 |   5 |  21 | GPIO.21 |  OUT | 0 | 29 || 30 |   |      | 0v      |     |     |
 |   6 |  22 | GPIO.22 |  OUT | 1 | 31 || 32 | 0 | IN   | GPIO.26 | 26  | 12  |
 |  13 |  23 | GPIO.23 |   IN | 0 | 33 || 34 |   |      | 0v      |     |     |
 |  19 |  24 | GPIO.24 |   IN | 0 | 35 || 36 | 0 | IN   | GPIO.27 | 27  | 16  |
 |  26 |  25 | GPIO.25 |   IN | 0 | 37 || 38 | 0 | IN   | GPIO.28 | 28  | 20  |
 |     |     |      0v |      |   | 39 || 40 | 0 | IN   | GPIO.29 | 29  | 21  |
 +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+
 | BCM | wPi |   Name  | Mode | V | Physical | V | Mode | Name    | wPi | BCM |
 +-----+-----+---------+------+---+---Pi 2---+---+------+---------+-----+-----+

Before diving into the code, let’s see the circuit. The LED’s positive (longer) pole is connected in series with a 220 Ohm resistor to the Pi’s 3,3 V power pin. The LED’s negative pole is connected to the Pi’s GPIO pin we want to program.

Blinking LED circuit

Now let’s see the header file! For explanations, visit Pieter’s website!

// source: www.pieter-jan.com/node/15

#include <stdio.h>

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> // this library has to be included too, otherwise map_peripheral doesn't work. source: elinux.org/RPi_GPIO_Code_Samples

#include <unistd.h>

#define BCM2708_PERI_BASE	0x3F000000
#define GPIO_BASE			(BCM2708_PERI_BASE + 0x200000)

#define BLOCK_SIZE 			(4*1024)
#define INPUT				0 // defining the GPIO function to use in my own function, the value has no significance
#define OUTPUT				1 // defining the GPIO function to use in my own function, the value has no significance
#define LOW					0 // defining the GPIO state to use in my own function, the value has no significance
#define HIGH				1 // defining the GPIO state to use in my own function, the value has no significance

struct bcm2836_peripheral
{
	unsigned long addr_p;
	int mem_fd;
	void *map;
	volatile unsigned int *addr;
};

struct bcm2836_peripheral gpio = {GPIO_BASE};

extern struct bcm2836_peripheral gpio;

int map_peripheral(struct bcm2836_peripheral *p)
{
   // Open /dev/mem
   if ((p->mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) { // without fcntl.h you get an error here
      printf("Failed to open /dev/mem, try checking permissions.\n");
      return -1;
   }
 
   p->map = mmap(
      NULL,
      BLOCK_SIZE,
      PROT_READ|PROT_WRITE,
      MAP_SHARED,
      p->mem_fd,      // File descriptor to physical memory virtual file '/dev/mem'
      p->addr_p       // Address in physical map that we want this memory block to expose
   );
 
   if (p->map == MAP_FAILED) {
        perror("mmap");
        return -1;
   }
 
   p->addr = (volatile unsigned int *)p->map;
 
   return 0;
}
 
void unmap_peripheral(struct bcm2836_peripheral *p) {
 
    munmap(p->map, BLOCK_SIZE);
    close(p->mem_fd);
}

// GPIO setup macros. Always use INP_GPIO(x) before using OUT_GPIO(x)
#define INP_GPIO(g)   *(gpio.addr + ((g)/10)) &= ~(7<<(((g)%10)*3))
#define OUT_GPIO(g)   *(gpio.addr + ((g)/10)) |=  (1<<(((g)%10)*3))
#define SET_GPIO_ALT(g,a) *(gpio.addr + (((g)/10))) |= (((a)<=3?(a) + 4:(a)==4?3:2)<<(((g)%10)*3))
 
#define GPIO_SET  *(gpio.addr + 7)  // sets   bits which are 1 ignores bits which are 0
#define GPIO_CLR  *(gpio.addr + 10) // clears bits which are 1 ignores bits which are 0
 
#define GPIO_READ(g)  *(gpio.addr + 13) &= (1<<(g))

// my own functions using Pieter-Jan's code

void gpio_inout(int io, int pin)
{
	if (io == INPUT)
		INP_GPIO(pin);
	
	if (io == OUTPUT)
	{
		INP_GPIO(pin); // if you want to set a pin as output, always set it as input first, for reasons see Pieter's explanation
		OUT_GPIO(pin);
	}
}

void gpio_set(int state, int pin)
{
	if (state == LOW)
		GPIO_SET = 0 << pin;
	if (state == HIGH)
		GPIO_SET = 1 << pin;
}

void gpio_clear(int pin)
{
		GPIO_CLR = 1 << pin;
}

void gpio_read(int pin)
{
		GPIO_READ(pin);
}

Now let’s see the c file, where I put my custom functions in use. It’s important, that you have the header file and the c file in the same directory.

#include "rpi2.h" // you have to have the header file and the c file in the same directory for this to work

int main(int argc, char **argv)
{	
	int pin = 27; // this code uses the BCM GPIO numbering
	
	if(map_peripheral(&gpio) == -1) 
	{
		printf("Failed to map the physical GPIO registers into the virtual memory space.\n");
		return -1;
	}
	
	gpio_inout(OUTPUT, pin); // set pin as output
	
	while(1)
	{
		gpio_set(HIGH, pin); // set pin high
		sleep(1);
 
		gpio_clear(pin); // clear pin
		sleep(1);
	}
	
	return 0; 
}

If you get your circuit right, this code will make a LED blink without installing any special libraries. The cool thing is, that once you know how to set a pin’s function and state, i. e. you know which bits you have to set, you can write your own code in plain vanilla C to do pretty much anything.

Don’t forget to check these sources out:
http://www.pieter-jan.com/node/15
http://elinux.org/RPi_GPIO_Code_Samples

Tagged with: ,
Posted in Programming, Raspberry Pi

TaoTronics TT-BH07 and Sony SBH20 Bluetooth Headset Review

Nexus 5X with the TaoTronics TT-BH07

Nexus 5X with the TaoTronics TT-BH07

Listening to podcasts, music, YouTube and using Skype on my phone is something I do almost daily. I’ve always been using wired headsets that came with the devices I had, but with time, having to bother with wires became rather uncomfortable. Wires are so limiting and in the age of Bluetooth, they’re not always necessary any more. As I later found out, making calls with Google Now with a Bluetooth headset while your phone is somewhere on you or around you is super amazing! After all, I started to hunt for a nice wireless headset on Amazon for my Nexus 5X, which itself came with none at all (for 530 €!).

First I went for a Sony SBH20 (35 €), which had a lot of good reviews, a nice look and a good brand name of course. When I got it, I had to realize, that even the lowest volume setting was unbearably loud. As I researched the problem I found out, that a change in Android 6 broke the granularity of volume control for quite a few Bluetooth devices. More specifically, the Bluetooth headset’s and the phone’s system volume had been integrated, which meant that the volume steps on the Sony headset were just not enough for a fine volume control. I tested the headset with my wife’s Samsung Galaxy S4 running Android 5.0.1 and my Windows 10 tablet and it worked as expected with both (the two volumes not being integrated). Since I needed the headset for my Nexus 5X, I had to return it and find something else. Also, the Sony SBH20 didn’t work with Skype for Android and it had only Bluetooth 3.0. Its killer feature was NFC, which made the pairing process a dream, but it wasn’t the reason I bought it.

My next and final choice was the ToaTronics TT-BH07. Although I had never heard of this brand before, it had many positive reviews and an even more appealing look and form factor than the Sony. It only consists of the wire with the earbuds on both ends and the control buttons in between. The earbuds magnetically stick together, so you can wear it like a necklace when you’re not using it. It’s extremely small, light and compact, which makes it the most comfortable and best usable headset I’ve ever had. It also has Bluetooth 4.1 (interestingly no LE) and it promises 5 hours of battery life. Sound quality is also very good. And the whole thing costs about 30 €. The only thing I miss is NFC, but I guess it would add bulk and reduce battery life, so I don’t mind this omission. The most important thing for me is the granularity of volume control with my Nexus. With music, it’s still not ideal, but bearable. With Soundcloud, YouTube, phone calls and Skype it’s absolutely OK. Yes, it works with Skype for Android, even with the camera turned on. It also comes with a nice little travel pouch. There are similar headphones for 80 and 120 € from Plantronics and Jaybird, but I don’t think, that they would be that much better. This TaoTronics headset for about 30 € is amazing!

TaoTronics TT-BH07

TaoTronics TT-BH07

Just a few words on Android 6 breaking volume granularity wit Bluetooth devices. It seems, that the blame for this problem cannot be put on Android 6 entirely, but it also depends on specific Bluetooth devices. I’ve got a Rokono B10 Bluetooth speaker at home. When paired with my Nexus 5X, volume control is just as fine as it can be. It has no problem at all.

All in all, the TaoTronics TT-BH07 is much more compact, lighter, more comfortable and has a newer Bluetooth version (4.1) than the Sony SBH20 (3.0), which makes it a better choice in my opinion. The TaoTronichs also works with Skype for Android, while the Sony does not. Battery life should be even, about 5 hours for both. The only big advantage of the Sony is NFC. It really makes a difference, but the better form factor and updated Bluetooth version of the TaoTronics easily outweigh it. Moreover the TaoTronics can be paired and used with two devices simultaneously, I’ve tried it. In my experience, TaoTronics is the clear winner here.

TaoTronics TT-BH07

+ great form factor, compact, small and light
+ magnetic earbuds
+ Bluetooth 4.1
+ works well with Android 6
+ works with Skype for Android
+ can be paired with 2 devices simultaneously
+ good price

– no NFC

Sony SBH20

+ NFC

– volume granularity is broken with Android 6
– doesn’t work with Skype for Android
– Bluetooth 3.0

Tagged with: , ,
Posted in Reviews

Sorting Algorithm in C

Sorting characters and numbers is a basic task and writing your own function for that is a great way to learn programming. Also, as far as I know, there’s no such functions included in standard C libraries, so you have to write your own code anyways.

The algorithm I wrote loops through an array and compares each element to the next one. If the next element is greater than the previous one, the two swap places – if the desired order is ascending. The idea is very simple, but writing properly working functions requires some experimentation.

I wrote my functions in a header file, because including your own .h file in a program and seeing your functions work is awesome. It is also convenient to reuse, but nothing beats the experience!

My header file starts with declaring some variables and the functions:

char asc = 'a', desc = 'd';           //variables to define sort order in functions
void sorts(char arr[], char o);       //function for sorting characters
void sortd(int arr[], int n, char o); //function for sorting digits
int slength(char s[]);                //function for determining string length

The logic for sorting characters and numbers is the same, but there is an important difference in implementation. If you sort characters, you can use the strlen function in the string.h library to determine how many times the loops in the algorithms should run, but I wrote my own function for that. That’s why my string sorting function has only two parameters: the string array and a character determining the order. If you sort numbers, the function either needs a plain integer parameter or you have to play around with pointers to determine the length of the array. I chose the simpler method for now. The reason is, that in digit arrays there is no '\0' special character to mark the end of the array as with string arrays. You can determine the length of a digit array using this trick:

int number_of_elements = sizeof(array) / sizeof(array[0])

However, if you pass number_of_elements into a function, it won’t work. You need to use pointers and it adds complexity I feel unnecessary for now. On the opposite, switching sort order is extremely simple, as you will see in the code.

Function to sort a string:

void sorts(char arr[], char o) //o determines sort order
{
	int i, j, temp;
	int length = slength(arr); //determine string length

	for (i = 0; i < length-1; i++)
	{
		for (j = 0; j < length-1; j++)
		{
			if (o == 'a') //ascending order char asc = ‘a’
			{
				if (arr[j] > arr[j+1]) //if element j is greater than j+1
				{
					temp = arr[j];     //save j in temp
					arr[j] = arr[j+1]; //swap j with j+1
					arr[j+1] = temp;   //replace j+1 with original j
				}
			}
			if (o == 'd') //descending order char desc = ‘d’
			{
				if (arr[j] < arr[j+1])
				{
					temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
	}
}

Function to sort numbers:

void sortd(int arr[], int n, char o)
{
	int i, j, temp;

	for (i = 0; i < n-1; i++)
	{
		for (j = 0; j < n-1; j++)
		{
			if (o == 'a')
			{
				if (arr[j] > arr[j+1])
				{
					temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
			if (o == 'd')
			{
				if (arr[j] < arr[j + 1])
				{
					temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
	}
}

Function to determine string length:

int slength(char s[])
{
	int i;
	for (i = 0; i < 100; i++)
	{
		if (s[i] == '\0')
		{
			return i;
		}
	}
}

I use CodeBlocks and if you want to include your own header file in source code, you have to configure the IDE to look for it in the right place: Settings -> Compiler -> Search directories -> Add – at least I think. Save your functions in a .h file and add its folder here.

An exaple code for sorting digits:

#include <stdio.h>
#include <stdlib.h>
#include <sort.h> //my custom header file including the sorting functions
#define NELEM(x) (sizeof(x) / sizeof(x[0]))
//NELEM for determining the number of elements in an array
//but you can’t pass its result into the function as it is
//because it won’t work for some C reason

int main()
{
    int i;
    int nums[5] = {3,5,1,7,2};

    printf("Unsorted array: ");
    for (i = 0; i<NELEM(nums); i++)
    {
        printf("%d", nums[i]);
    }
    printf("\n\n");
    printf("Sorted array in ascending order: ");
    sortd(nums,5,asc);
    for (i = 0; i<NELEM(nums); i++)
    {
        printf("%d", nums[i]);
    }
    printf("\n\n");
    printf("Sorted array in descending order: ");
    sortd(nums,5,desc);
    for (i = 0; i<NELEM(nums); i++)
    {
        printf("%d", nums[i]);
    }
    printf("\n");
    return 0;
}
Sorting digit array

Sorting a digit array

An example code to sort a string:

#include <stdio.h>
#include <stdlib.h>
#include <sort.h>
#define MAX 4

int main()
{
    char text[MAX];
    printf("Type string (max %d characters): ", MAX);
    scanf("%s", text);
    sorts(text, asc);
    printf("\nSorted string in ascending order: %s\n", text);
    sorts(text, desc);
    printf("\nSorted string in descending order: %s\n", text);

    return 0;
}
Sorting a sting

Sorting a sting

Programming is awesome!

Tagged with: , ,
Posted in Programming

Password Evaluation Algorithm in C

Have you ever wondered, how websites and applications check if your password contains the required characters? They do it by using algorithms and in this post I’d like to show you an example I’ve written in C.

If you learn programming in C, you’ll quickly find out that you can accomplish pretty much anything with loops and if else statements. By combining these in themselves incredibly simple building blocks, you can construct just as incredibly complex and powerful algorithms. Algorithms are the pieces of code that do even the most fundamental tasks like sorting data, finding characters in a text and so on. In higher level programming languages like C#, Java, C++ and even in C itself, standard algorithms for common tasks are readily available in the form of classes or functions. In most cases, those algorithms are more than good enough. However, there are two main reasons for writing your own code. One is obviously to create customized and optimized solutions for custom problems not covered by ready-made code. The other reason is to learn and understand how algorithms work, which is a must have skill for any good programmer.

Checking whether a password meets minimum requirements, for example that it contains at least one number, upper-case letter and a special character, is a fundamental task for any website or application. There are no doubt many pre-written algorithms to accomplish this task, but writing your own piece of code that actually works is very rewarding. The code I produced might not be the smartest, shortest or prettiest in the world, but it does exactly what it is supposed to do. It loops through each character of a string and checks if at least one number, upper-case letter and a dollar sign has been included. If it is so, it drops a “Good password!” message, if not, it instructs the user to include the required characters. The app also makes sure that the password meets a minimum and maximum length requirement.

First let’s see the headers and libraries you need:

#include <stdio.h>  //standard input and output
#include <stdlib.h> //standard library
#include <ctype.h>  //includes isupper() and isdigit() functions for obvious purposes
#include <string.h> //includes the strlen() function to check password length
#define MIN 5       //minimum length
#define MAX 11      //maximum length

These are the necessary variables:

char pwd[MAX];     //array containing the password
int upper[MAX];    //array for keeping track of upper-case letters
int num[MAX];      //array for keeping track of numbers
int dollar[MAX];   //array for keeping track of dollar signs
int sumUpper = 0;  //sum of upper-case letters in password
int sumNum =0;     //sum of numbers in password
int sumDollar = 0; //sum of dollar signs in password
int i = 0;         //index for the loops

To make sure that memory locations allocated to the arrays don’t contain any unwanted data, it’s always a good idea to initialize or “clean up” the arrays in advance:

for (i = 0; i < MAX; i++) //initializing the arrays makes sure they
{                         //start with "clean" memory locations
    pwd[i] = 0;
    upper[i] = 0;
    num[i] = 0;
    dollar[i] = 0;
}

You can use an if else statement to make sure the password meets length requirements:

if (strlen(pwd) >= MIN && strlen(pwd) < MAX) //if password meets minimum and
{                                            //maximum length requirement
    algorithm
}
else //if password doesn't meet minimum and maximum length requirements
    printf("\nYour password has to be between 4 and 10 characters!\n");

If the password isn’t too short nor too long, the actual algorithm can run. A for loop runs through each character of the password until the \0 special character is reached. This character signifies the end of each string in C. That’s why you have to be careful with manipulating the individual characters of strings: if this “invisible”, special character gets overwritten, it can cause real problems. Whenever an upper-case letter, a number or a dollar sign is found, a 1 is written to the corresponding position of the upper, num and dollar arrays:

for (i = 0; pwd[i] != '\0'; i++) //for loop runs until it reaches the
{                                //special \0 end of string character
    if (isupper(pwd[i]))         //if a character is upper-case, a 1 is written to
        upper[i] = 1;            //the corresponding location of the upper array
    if (isdigit(pwd[i]))         //same applies when a number is found
        num[i] = 1;
    if (pwd[i] == '$')           //same applies when a dollar sign is found
        dollar[i] = 1;
}

In the next steps the digits at each position of the upper, num and dollar arrays are added up. Adding up zeros amounts to zero, but adding up ones accurately indicates how many of the required characters are included in the password:

for (i = 0; i < MAX; i++) //the digits in each position of the
{                         //upper, num and dollar arrays are added up
    sumUpper += upper[i];
}                         //adding up zeros amounts to zero, but adding up
                          //ones accurately indicates how many of the required
for (i = 0; i < MAX; i++) //characters are included in the password
{
    sumNum += num[i];
}

for (i = 0; i < MAX; i++)
{
    sumDollar += dollar[i];
}

If sumUpper, sumNum and sumDollar are greater than one, it means that at least one of each required character has been included in the password, resulting in a “Good password!” message:

if (sumUpper > 0 && sumNum > 0 && sumDollar > 0)
    printf("\nGood password!\n");

Since the occurrences are summed up, you can easily adjust the minimum number to demand more than one of those characters. By expanding the algorithm with more loops and variables accordingly, you can also demand any other character you want.

If even one of the requirements is unmet, the user is instructed to include the required characters:

else
    printf("\nYou have to include at least one number, upper-case letter and dollar sign!\n");

There may be more efficient ways to accomplish this task, but figuring out something like this yourself is an important step to understanding how programs actually do what they do. If you look at this code more carefully, you will realiese that even the algorithm I’ve written includes other algorithms. Isupper, isdigit and strlen are all algorithms included in the ctype.h and string.h libraries, written by someone else. I don’t know how about you, but I have an unquenchable desire to understand how this kind of stuff works, even if I wouldn’t need to write my own code. By the way, I use CodeBlocks to program in C and I recommend the video tutorials on thenewboston.com to get started.

Finally, let’s see the whole code in one chunk:

#include <stdio.h>  //standard input and output
#include <stdlib.h> //standard library
#include <ctype.h>  //includes isupper() and isdigit() functions for obvious purposes
#include <string.h> //includes the strlen() function to check password length
#define MIN 5       //minimum length
#define MAX 11      //maximum length

int main()
{
    char pwd[MAX];     //array containing the password
    int upper[MAX];    //array for keeping track of upper-case letters
    int num[MAX];      //array for keeping track of numbers
    int dollar[MAX];   //array for keeping track of dollar signs
    int sumUpper = 0;  //sum of upper-case letters in password
    int sumNum =0;     //sum of numbers in password
    int sumDollar = 0; //sum of dollar signs in password
    int i = 0;         //index for the loops

    for (i = 0; i < MAX; i++) //initializing the arrays makes sure they
    {                         //start with "clean" memory locations
        pwd[i] = 0;
        upper[i] = 0;
        num[i] = 0;
        dollar[i] = 0;
    }

    printf("Your password has to include at least one upper-case letter, number and dollar sign!\n\n");
    printf("Type in your password: ");

    scanf("%s", pwd); //storing the password

    if (strlen(pwd) >= MIN && strlen(pwd) < MAX)   //if password meets minimum and maximum length requirement
    {
        for (i = 0; pwd[i] != '\0'; i++) //for loop runs until it reaches the
        {                                          //special \0 end of string character
            if (isupper(pwd[i]))                   //if a character is upper-case, a 1 is written to
                upper[i] = 1;                      //the corresponding location of the upper array
            if (isdigit(pwd[i]))                   //same applies when a number is found
                num[i] = 1;
            if (pwd[i] == '$')                     //same applies when a dollar sign is found
                dollar[i] = 1;
        }

        for (i = 0; i < MAX; i++) //the digits in each position of the
        {                         //upper, num and dollar arrays are added up
            sumUpper += upper[i];
        }                         //adding up zeros amounts to zero, but adding up
                                  //ones accurately indicates how many of the required
        for (i = 0; i < MAX; i++) //characters are included in the password
        {
            sumNum += num[i];
        }

        for (i = 0; i < MAX; i++)
        {
            sumDollar += dollar[i];
        }

        if (sumUpper > 0 && sumNum > 0 && sumDollar > 0) //If sumUpper, sumNum and sumDollar are greater than one,
            printf("\nGood password!\n");                //it means that at least one of each required character
        else                                             //has been included in the password
            printf("\nYou have to include at least one number, upper-case letter and dollar sign!\n");
    }
    else //if password doesn't meet minimum and maximum length requirement
        printf("\nYour password has to be between 5 and 10 characters!\n");

    return 0;
}
Tagged with: , ,
Posted in Programming

Continuing For Loop in C

Recently I’ve been concentrating on learning C instead of C# for a number of reasons. First, C is the grandpa of many other languages like C#, Java, Python and PHP. Second, despite of its age, C is still one of the most important languages today. It’s a general purpose language with which you can target almost any platform from Windows to Linux and it’s more suitable for programming low-level applications for devices like networking equipment and robots. One very good, IT-related example is OMI providers, which are written in C to make switches, routers and other less-powerful devices manageable for IT pros. You can read about this in Don Jones’ article here. Third, this is the language we are learning at school form the 2nd semester on, C# having only been an introduction to programming.

At school we are using Visual Studio to code in C, but Microsoft’s IDE has really been designed for C++, C# and alike. My favorite IDE for programming in C is the open-source and cross-platform CodeBlocks. By saving my projects in Dropbox, I can easily work on my Windows and Linux machines, which is absolutely awesome. There are many C tutorials on the internet, but the ones I most like are the videos made by Bucky Roberts on TheNewBoston.com. If you’re a beginner like me, I suggest you start there.

In any programming language, loops are essential parts of even simple command line applications. The app I wrote calculates the average of an arbitrary number of test scores. Based on the average, it also determines a grade from 5 to 1. These are simple tasks, but you can learn very useful things by programming them. First, the app asks the user for the number of tests taken. Then, with the help of a for loop, it asks for each individual score to calculate the average and the final grade.

Calculating avrage and final grade

This is all great, but good programming also involves error handling. In my app I only handled the most obvious errors that could occur. First, you need at least two scores to calculate an average. This is easily handled by an if else statement. Second, any score has to be 0 or greater. Why would anyone want to type in a number less than 0 doesn’t matter. Calculating with negative numbers makes no sense in this program, so you have to handle it. To do this, you have to write your for loop in a way, that it asks for the score again and again, until a correct number is supplied. Also, the loop cannot be exited until the score for each test is collected. For example, if you have 5 tests, the for loop will run five times to ask you for the individual scores. If you supply a negative number at the 3rd round, the program has to keep asking for the 3rd score until you type in a 0 or greater number and the loop has to continue from there. It must not exit prematurely (you can use the break statement to exit a loop earlier). This can be done by using the continue statement, like this:

for (i = 0; i < [number of tests]; i++) // the loop runs as many times as many tests were taken
{
    printf("Score %d: ", i+1); // each run asks for the individual score, i+1 is neededd beacause the loop starts with 0
    scanf("%f", &score);       // reads the score
    if (score >= 0)            // if the score is 0 or greater, it's added to the sum
        sumOfScores += score;  // sumOfScores = sumOfScores + score
    else                       // else the loop continues, i.e runs again
    {
        printf("Score cannot be less than 0!\n");
        i--;                   // i-- makes sure that the score of the same test will be asked again
        continue;              // as if the round with the incorrect score never happened
    }
}

That’s how it looks in action:

For loop continues when supplied negative number

When calculating the average, you have to be careful with the data types, lest you may get incorrect results. In this case, you calculate the average by dividing the sum of scores by the number of tests. The average and the sum of scores should be floats, but the number of tests has to be an integer, obviously. C doesn’t like mixing different data types in calculations, so you have to make the number of tests a float just for that one line of code with type casting:

average = sumOfScores / (float)tests;
// by type casting you can make tests, which is an integer, a float just for this calculation

The rest should be quite straightforward, so let’s see the complete code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int tests;         // number of tests taken
    float score;       // score of each test
    float sumOfScores; // sum of the scores
    float average;     // sumOfScores / tests
    int grade;         // 1-5
    int i;             // index for the loop

    printf("Number of tests: "); // asking for the number of tests taken
    scanf("%d", &tests);         // reading the answer
    printf("\n");                // printing a new line to make things look better

    if (tests >= 2) {                  // you need at least 2 tests to calculate an average
        for (i = 0; i < tests; i++) {  // asking for the score of each individual test until the number of tests is reached
            printf("Score %d: ", i+1); // i+1 because the loop starts form 0
            scanf("%f", &score);       // reading the score
            if (score >= 0)            // each score has to be 0 or greater
                sumOfScores += score;  // each score is added to the sum of the previous scores, same as sumOfScores = sumOfScores + score
            else {                     // if score is less than 0
                printf("Score cannot be less than 0!\n");
                i--;                   // this round must not count, since the score is incorrect
                continue;              // continue the loop without exiting, you can exit with break;
            }
        }

        average = sumOfScores / (float)tests; // calculating average
                                              //(float) makes tests, which is an integer, a float just for this calculation
        if (average >= 90)                    // calculating final grade
            grade = 1;                        // you don't need {} if you have only one line of code after if, else if and else
        else if (average >= 80)
            grade = 2;
        else if (average >= 70)
            grade = 3;
        else if (average >= 60)
            grade = 4;
        else
            grade = 5;

        printf("\nAverage:\t%.2f\nGrade:\t\t%d\n", average, grade); // printing results

    }
    else
        printf("You need at least 2 tests to calculate the average!\n"); // if someone defined only one test for instance

    return 0;
}

This small app is far from being perfect, but it’s a good excercise. For example, if you type in letters or anything nonsense instead of numbers, the program just goes on and calculates an incorrect result of course. This kind of error is easy to handle with try catch statements in C#, but in C you have to code your own functions for that.

Tagged with: , ,
Posted in Programming

Resize Windows VM’s Virtual Disk in CentOS 7 KVM

In the past weeks, I’ve been playing with KVM (Kernel Based Virtual Machine) virtualization on my CentOS 7 box. I installed a Windows Server 2012 R2 Server Core instance with only 10 GB of virtual storage. Later I decided that I wanted to increase the disk’s size, but I didn’t find a way to do it in the GUI-based Virtual Machine Manager. Of course, there is a much more capable command line tool called virsh to manage virtualization. I wanted to dive into it anyways and this was an excellent opportunity to get started.

First, I looked through the available commands by typing virsh help in the Terminal. I tried to list my VM’s with the virsh list command, but got no result. That was weird. Apparently you have to issue the following command to see your VMs:

[i@localhost ~]$ sudo virsh list --all
 Id    Name                           State
----------------------------------------------------
 -     WIN10                          shut off
 -     WS2012R2                       shut off

By the way, I couldn’t get Windows 10 Preview work. It hung up after installation and gave me a black screen no matter what I did. Next, you can check out your VM’s virtual disks with vol-list:

[i@localhost ~]$ sudo virsh vol-list --pool default
Name                 Path                                    
-----------------------------------------
WIN10.img            /var/lib/libvirt/images/WIN10.img       
WS2012R2.img         /var/lib/libvirt/images/WS2012R2.img

You can view a lot more configuration information by dumping a VM’s XML file. Look for the virtual disk under devices (lines 23 and 25):

[root@localhost i]# sudo virsh dumpxml WS2012R2
<domain type='kvm'>
  <name>WS2012R2</name>
  <uuid>d3260f99-4e1c-4825-832a-e313df2615ba</uuid>
  <memory unit='KiB'>2072576</memory>
  <currentMemory unit='KiB'>2072576</currentMemory>
  <vcpu placement='static'>1</vcpu>
  <os>
    <type arch='x86_64' machine='pc-i440fx-rhel7.0.0'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
    <apic/>
    <pae/>
  </features>
  <clock offset='localtime'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>restart</on_crash>
  <devices>
    <emulator>/usr/libexec/qemu-kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='raw' cache='none'/>
      <source file='/var/lib/libvirt/images/WS2012R2.img'/>
      <target dev='hda' bus='ide'/>
      <address type='drive' controller='0' bus='0' target='0' unit='0'/>
    </disk>
    <disk type='file' device='cdrom'>
      <driver name='qemu' type='raw'/>
      <source file='/home/i/Downloads/ISO/WS2012R2-Standard/en_windows_server_2012_r2_x64_dvd_2707946.iso'/>
      <target dev='hdc' bus='ide'/>
      <readonly/>
      <address type='drive' controller='0' bus='1' target='0' unit='0'/>
    </disk>
    <controller type='usb' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x2'/>
    </controller>
    <controller type='pci' index='0' model='pci-root'/>
    <controller type='ide' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
    </controller>
    <controller type='virtio-serial' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
    </controller>
    <interface type='direct'>
      <mac address='52:54:00:44:23:f2'/>
      <source dev='enp0s25' mode='vepa'/>
      <model type='rtl8139'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>
    <serial type='pty'>
      <target port='0'/>
    </serial>
    <console type='pty'>
      <target type='serial' port='0'/>
    </console>
    <channel type='spicevmc'>
      <target type='virtio' name='com.redhat.spice.0'/>
      <address type='virtio-serial' controller='0' bus='0' port='1'/>
    </channel>
    <input type='tablet' bus='usb'/>
    <input type='mouse' bus='ps2'/>
    <graphics type='spice' autoport='yes'/>
    <sound model='ich6'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
    </sound>
    <video>
      <model type='qxl' ram='65536' vram='65536' heads='1'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
    </video>
    <memballoon model='virtio'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x06' function='0x0'/>
    </memballoon>
  </devices>
</domain>

By default, the .img disk files are in /var/lib/libvirt/images/, the default pool. Next, resize the volume with vol-resize:

[i@localhost ~]$ sudo virsh vol-resize WS2012R2.img 25G --pool default
Size of volume 'WS2012R2.img' successfully changed to 25G

That’s great, but it’s only one half of the job. You also have to resize the disk partition within the guest OS. Let’s see how to do it with PowerShell. First, check out the disk and partition number with Get-Disk and Get-Partition:

Get-Disk and Get-Partition

As you can see, the disk size is 25 GB, but the C partition is just under 10 GB. Next, resize C: with this cmdlet:

$size = Get-PartitionSupportedSize -DiskNumber 0 -PartitionNumber 2
Resize-Partition -DiskNumber 0 -PartitionNumber 2 -Size $size.SizeMax

And it’s done:

Resized partition

I haven’t had to shrink a virtual disk yet, but it’s not much different from increasing it. Let’s say I wnated to shrink 25 GB down to 10 GB. To be safe, first I’d shrink the partition down to 9 GB within the VM. Next, I’d shrink the volume down to 10 GB in virsh. Then, I’d increase the partition size to 10 GB inside the VM, just as I showed it.

Hope you enjoyed!

Tagged with: , , , ,
Posted in Linux

Troubleshoot Refused VNC Connection in CentOS 7

The other day I connected to my CentOS 7 computer from Windows via RealVNC Viewer. Everything went fine, but after I left the machines unattended for a short time, the connection froze to the point that I had to shut CentOS down and boot it again. When I tried to connect again, I got an error message saying something like “The connection was refused by the host computer” or similar, I can’t remember exactly. I rebooted CentOS several times, but nothing changed. Now I had to connect a monitor and the necessary peripherals to the box and start troubleshooting.

First, I checked the status of the VNC service:

[root@localhost Desktop]# systemctl status vncserver@:2.service -l
vncserver@:2.service - Remote desktop service (VNC)
   Loaded: loaded (/etc/systemd/system/vncserver@:2.service; enabled)
   Active: failed (Result: exit-code) since Sat 2015-02-28 14:37:00 CET; 10min ago

Feb 28 14:37:00 localhost.localdomain systemd[1]: vncserver@:2.service: control process exited, code=exited status=2
Feb 28 14:37:00 localhost.localdomain systemd[1]: Failed to start Remote desktop service (VNC).
Feb 28 14:37:00 localhost.localdomain systemd[1]: Unit vncserver@:2.service entered failed state.

The VNC service apparently failed to start. If you don’t know why I used vncserver@:2.service, please read my earlier post about configuring VNC. I tried to start the service, but it kept failing:

[root@localhost Desktop]# systemctl start vncserver@:2.service
Job for vncserver@:2.service failed. See 'systemctl status vncserver@:2.service' and 'journalctl -xn' for details.

As I was digging through the internet, I found some clues about corrupted session files that had to be deleted to solve this problem. The files were supposed to be in the /tmp/.X11-unix directory (capital X11, Linux is case-sensitive!). When I checked the contents of /tmp, I found this:

ls /tmp

There was no /.X11-unix directory inside. The issue was, that this folder is hidden and such items can only be seen if you put -la after ls, like this:

ls -la /tmp

Now I saw the folder I was looking for at the end of the list. Inside /.X11-unix were the session files:

X2

The corrupted file belonging to “vncuser”, the user I configured for VNC access, was X2. I removed it with the rm /tmp/.X11-unix/X2 command. Then, I started the service, rebooted the computer and I was able to seamlessly connect to my CentOS machine through VNC.

Tagged with: , ,
Posted in Linux
Archives

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 167 other followers