Skip to main content

Sending text messages using AtomPark API

I have a SMS gateway built upon smsd and Huawei-1550 which is being used to receive and forward text messages. Recently I started checking the stats for the account and found that I am not using the whole SMS package I am paying for so I decided to look into alternative ways of sending those messages.

After searching for the gateways that have a public API I decided to try “AtomPark”. It is also known as ePochta and is accessible from a dozen of web sites:

They specialize in Bulk SMS Text Messaging, yes, the messages that are notifying you about some sale or ask you to visit some site may be coming from such kind of company…

Well, I am going to use their gateway for much more useful purpose.

All the examples they have on their docs on API v2.0 and docs on API v3.0 are provided in PHP, I am using Python and I failed to find the examples in any other language.

It turned out that the integration is not that straightforward so I decided to write this blog post to tell about the issues I had while trying to make use of the service.

There are two API versions, first is XML-based and may look simpler but I suggest you to use v3 instead as it generally better.

API v2.0

First of all, the only way you can pass the parameters in v2.0 is through POST request in multipart/form-data format (the one with boundaries and such), the service does not accept the application/x-www-form-urlencoded format but fails to tell you about the problem.

HTTP/1.1 200 OK'
Date: Sat, 04 Aug 2012 12:57:57 GMT
Server: Apache/2.2.19 (FreeBSD) mod_ssl/2.2.19 OpenSSL/0.9.8n DAV/2 PHP/5.3.6
with Suhosin-Patch
X-Powered-By: PHP/5.3.6
Content-Length: 0
Content-Type: text/html

So first of all, write a routine that will encode the “XML” parameter into multipart/form-data. See the example below.

In case you are using ElementTree (or any other library to build the XML) you may start getting a weird response:

<?xml version="1.0" encoding="UTF-8"?>
<RESPONSE>
<status>-2</status>
<credits>0</credits>
</RESPONSE>
</code>

According to the documentation, that means the XML is not valid. After a ton of debugging I found out that the gateway itself is not a good XML parser and fails to parse the document if it is missing newlines. This can be fixed by reformatting the document (found the code in Doug Hellmann’s article).

API v3.0

This version is just a bit more complex at the authentication stage but it works with both types of POST encoding (no need for that boundary) and the response is generated as a JSON document.

The only thing you need to know is that you will have to include version and action parameters too (which seems to be an overkill – the URL already has the version and action embedded).

The signature calculation is straightforward too. It looks like it was modelled after Facebook’s old authentication system.

Here’s the complete example – PUBLIC_KEY and PRIVATE_KEY can be obtained from your settings page at AtomPark member area:

That code can be seen as a starting point. Their rates for Ukrainian numbers are 0.14₴ (about $0.018) and that makes it a perfect service to send the notification messages from.

Податкова звітність - безкоштовні ключі від податкової

/galleries/dropbox/tax-office-ad.jpg

На вулицях Києва зараз можна побачити рекламу нового сервісу Державної податкової служби України – безкоштовна видача ключів для електронно-цифрового підпису документів.

З самого початку ведення підприємницької діяльності я використовував ключі компанії “ІВК” для подання звітів. Оскільки мій сертифікат нещодавно втратив чинність, я вирішив отримати новий ключ та сертифікат в АЦСК Державної податкової служби України

PDF варіанти документів було створено у Web Word App через сервіс Microsoft Windows Live SkyDrive на випадок, якщо Microsoft Office під рукою немає. Будь ласка, перевірте, що дані в бланках співпадають з оригінальними .doc файлами.

Під час підготовки документів виявилося, що моє свідоцтво про державну реєстрацію також втратило чинність місяць тому (я забув), тепер потрібно отримати виписку з Єдиного державного реєстру юридичних осіб та фізичних осіб-підприємців. Виписку можна отримати тільки у Державного реєстратора за місцем реєстрації. Вартість виписки - 17 гривень. Для отримання виписки потрібно подати заяву. Бланк заяви можна завантажити, наприклад, звідси (PDF версія).

/galleries/dropbox/exerpt-head.jpg

Для отримання ключів потрібні наступні документи:

  • Заява на реєстрацію (заповнена власноруч, pkirq1.pdf)

  • Заява-приєднання до договору (заповнена власноруч у двох екземплярах, ppkirq2.pdf)

  • Копія виписки або витягу з Єдиного державного реєстру (завірена власноруч)

  • Копія довідки про присвоєння ідентифікаційного коду (завірена власноруч)

  • Копія 1-4 сторінок паспорту (завірена власноруч)

Також потрібно мати носій для ключа, наприклад USB “флешку” (програмне забезпечення записує файл Key-6.dat в корінь носія, якщо потрібно отримати ще й печатку, то доведеться або використовувати два носія, або брати з собою комп’ютер та переписувати ключі).

Територіальної прив’язки немає. Тобто отримати ключі можна в будь-якому відділенні, що вказані на сторінці контактної інформації.

Як я вже казав, приватна частина (ключ) записується на носій користувача, публічна частина (сертифікат) публікується через декілька хвилин на сайті.

/galleries/dropbox/tax-office-entry.png

Сертифікат вже у системі, але він ще не прив’язаний до вашого облікового запису у ДПС. Якщо намагатися відправити звіт, то у відповідь отримаємо знайоме <http://rtg.in.ua/2011/03/16/tax-office-reports-via-email/>_:

Блок даних. Невірний підпис - сертифікат відсутній в базі сертифікатів (ЄДРПОУ: ‘3142520172’, серійний №: ‘69D67841CA65A4AB04000000962B0000DF2A0000’, виданий ‘Єпішев Роман Олегович’)

Якщо раніше після отримання сертифікату було потрібно їхати до податкової з носієм, то зараз процедура значно спростилася – достатньо відправити на шлюз електронної звітості підписаний договір про визнання електронних ключів. Підписувати договір потрібно після кожної заміни сертифікатів.

Договір можна сформувати у програмному забезпеченні ДПС, що завантажується з сайту АЦСК ДПС – http://www.cskidd.gov.ua/program_obespech.

/galleries/dropbox/tax-office-agreement-head.png

Всі поля обов’язкові, у “Місцезнаходженні” окрім фізичної адреси треба вказати email та номер телефону. У полі “в особі” зі сторони податкової треба вказати начальника вашої ДПІ, або його заступника - це вже краще дізнатися у самій ДПІ. В моєму випадку я вказав дані начальника, на що отримав відповідь:

Виявлені помилки: невірний реквізит:В ОСОБІ- заступник начальника Броварської ОДПІ Київ.обл. ДПС-Малихіна О.М.

Після цього я вказав коректні реквізити, надіслав документ знову. Через деякий час отримав XML документ з повідомленням про підписання договору:

Договір підписаний між: Фізична особа - підприємець Єпішев Роман Олегович та ДЕРЖАВНА ПОДАТКОВА АДМІНІСТРАЦІЯ УКРАЇНИ

Все, можна відправляти декларацію.

До речі, якщо ви сформували декларацію, але отримуєте наступне у відповідь -

Виявлені помилки: Помилка - форма не приймається в періоді ‘2012 р.,II Квартал’.

це значить, що потрібно у самому звіті і під час збереження вибрати не “Другий квартал”, а “Півріччя” – про це дізнався тут.

Samsung HMX-H300 firmware upgrade

/galleries/dropbox/sg_HMX-H300BP-SEA_001_Front.jpg

I found the Samsung HMX-300 camcorder to be a bit unstable during some actions, it failed to initialize 32GB SDHC card properly in the beginning and could hang indefinitely after USB operation. I decided to look for a firmware update.

The support page with firmware download does not have an instruction for an upgrade in English and I was not able to update the firmware – the camcorded did not ask me to do this even when I copied the file (zip or unzipped) to the card. Then I found the proper article on korean Samsung web site So, here’s what needs to be done for manual firmware upgrade:

  • Download the firmware archive file (h300_FW_1204131.zip) and unzip the contents (single h300_firmware.bin file) to the root of the SD card.

  • If the battery charge level is less than 3 points, the camcorder will not attempt to update the firmware.

  • Turn on the camera with SD card containing the firmware update, a dialog box will appear asking you whether you want to upgrade.

  • After upgrade is completed the camcorder will be automatically turned off and the firmware file will be deleted from the SD card.

My mistake was that I tried the update when the battery was not full (3 points is the 100% charged battery). After the battery was completely charged the upgrade went through perfectly.

Шум в Zoom H1

В прошлую пятницу я приобрел диктофон Zoom H1 в portativ.ua. В магазине я проверил его на работоспособность и поехал домой счастливый.

Дома же я обнаружил, что по какой-то причине правый канал вместо тишины записывал шум. Такой же шум я ранее слышал на некоторых моделях материнских плат, когда пользователь двигал мышкой – наводки. В аудиофайле ниже в правом канале можно услышать то, о чем я говорю:

Сначала я решил, что это не есть значительный дефект, однако на некоторых записях помехи были слышны лучше, чем сигнал. Убрать шум в audacity полностью не удавалось.

В сети нашел несколько одиноких сообщений о похожих шумах, и даже один звуковой файл с “пульсирующим” шумом (в записи выше наблюдается и такое).

Сегодня я пообщался с представителем интернет-магазина и уточнил порядок обмена устройства. После этого приехал в оффлайн-магазин на станции метро “Льва Толстого” и через 10 минут я уже проверял новый экземпляр.

Без каких-либо вопросов мне заменили устройство, персонал магазина приятно удивил.

Итак, если идете покупать диктофон, то возьмите с собой проверенные наушники и попытайтесть провести запись на максимальном уровне чувствительности (Level 100). Не должно быть электрических шумов или периодических пульсаций.

Вот запись улицы на исправном Zoom H1:

Диктофон продают уже с прошивкой 2.0, в которой добавили функциональность USB Audio, и его теперь можно использовать как USB микрофон и динамик. Ubuntu/Alsa/PulseAudio работают с устройством без проблем.

OpenStack Swift and Keystone. Setting up Cloud Storage

Having played a lot with HP Cloud and Canonical OpenStack installation, I decided to install OpenStack on my own home server. In order to gain better understanding about all the processes involved I decided not to use devstack script and follow the installation guides with the packages already available in Ubuntu Server 12.04 LTS (Precise Pangolin).

Surprisingly, setting up Keystone, Nova Compute, and Glance went really well with almost no effort from my side and I was even able to launch an instance of Ubuntu Server 12.04 running in nested KVM, which in turn was running on Compute virtual instance in KVM. So I had 2 levels of virtualization and it was still working quite well.

Then I decided to make Swift (Object Store) authenticating against Keystone (instead of built-in swauth). And this took a bit longer than expected.

/galleries/dropbox/storage-proxy.png

Read more…

Чем я пользуюсь

Для работы мне требуется несколько вещей, в этом посте я опишу интернет провайдера, банк и оборудование, которыми я пользуюсь.

Интернет

Одним из условий подписания контракта с Canonical было наличие стабильного подключения к Интернет. После года попыток наладить нормальное подключение с домашним интернетом Билайна (теперь Киевстар, но VPN костыль у них никуда не делся) я решил перейти на akson45. За 2 года работы с этим провайдером суммарно связь пропадала на 8 часов (99.96% up) а в техническую поддержку потребовалось звонить два раза, первый раз - при подключении внешнего IP адреса, второй - уже во время падения канала связи.

С билайном я помнил телефон службы поддержки наизусть.

Банк

Уже долгое время я являюсь клиентом Piraeus Bank МКБ и пользуюсь практически всем спектром услуг - платежными картами, расчетными счетами, интернет-банкингом для физический лиц и предпринимателей. Специалист банка, Ольга Виценко, помогла разобраться в тонкостях работы с зарубежным клиентом и радостно отвечала на все мои вопросы (иногда довольно глупые) касательно банковских процессов, за что я ей очень благодарен.

Использование интернет-банкинга позволило оплачивать услуги различных компаний без комиссии, через стандартный банковский перевод. А SMS оповещение о транзакциях позволило создать достаточно простую и удобную систему учета расходов, о которой, возможно, я напишу в следующий раз.

Для того, чтобы поиграться с [НСМЕП], я завел карту в Экспресс-Банке. Отношение к нему нейтральное. Сайт не содержит тарифов по обслуживанию карты, а для того, чтобы узнать о новых тарифах, требуется приехать в отделение. Почему-то для получения листка с тарифами, требуется предоставить свой паспорт. Тем не менее, их НСМЕП карта работает и я время от времени пересобираю wine с поддержкой смарт-карт в своем PPA. [НСМЕП]: http://clubs.ya.ru/4611686018427461168/3 Про Національну Систему Масових електронних платежів

Оборудование

Рабочий ноутбук у меня - Lenovo E420 (после того, как Acer Aspire 5520 сжег себе видеокарту). На батарее 25++ 94Wh (которую пришлось покупать в США, т.к. в Украине рынок батарей какой-то странный) система обещает проработать 6 часов. Этот ноутбук не может похвастаться низким энергопотреблением (сравнение здесь - тестирование RC6), однако у него очень удобная клавиатура, отличный экран и технические характеристики).

Между моей локальной сетью и сетью провайдера находится TP-Link TL-WR1043ND под управлением OpenWRT. Он служит как маршрутизатором, так и точкой доступа в режиме 802.11g (хотя позволяет и .11n). Дополнительно он выступает как шлюз в IPv6 сеть NetAssist и OpenVPN сервером на случай необходимости подключения к рабочим ресурсам, которые не защищены SSL.

В моей локальной сети есть также сервер, который используется как хост для хранения данных, вируальных машин различного назначения. Используется четырехъядерный AMD Athlon™ II 630 @ 2.8Ггц. На материнскую плату Asus M4A785T-M установлено 8Гб памяти, в качестве жестких дисков выступают 2x1.5Тб Seagate ST31500341AS после того, как при скачке напряжения вышли из строя 2 винчестера Samsung SpinPoint F3 (как оказалось, довольно обычное явление для этих дисков). В сеть подключены 2 гигабитные карты (RTL 8168B на материнской плате и D-Link DGE-528T). Требуется обе, так как при использования моста для виртуальных машин включение или выключение одной из них приводит к временному зависанию сети на данной карте (видимо, из-за перестройки топологии).

На сегодня все, надеюсь из данного поста удалось получить немного полезной информации. Удачи!

Міжрегіональний центр видачі паспортів – отримання документів

/galleries/dropbox/passport-ua-building.jpg

Місяць тому я подав документи у Міжрегіональний центр видачі паспортів, а вчора отримав новий паспорт.

Знову їздив двічі, цього разу через те, що пропустив наступний пункт у правилах:

Після закінчення відповідного терміну для отримання паспорта громадянина України для виїзду за кордон необхідно з внутрішнім паспортом та (за наявності) діючого закордонного підійти до робочих місць 8,9.

Дата видачі у самому паспорті – 10 квітня, тобто документ був готовий через 16 робочих днів.

Видача паспортів працює протягом усього робочого дня центру і займає 5 хвилин, але зранку люди створюють чергу на отримання паспортів ще до відкриття центру.

A Brand New Ubuntu One Indicator for Precise

About two years ago I published the post on Ubuntu One Indicator, which at that time simply displayed the current synchronization state right from syncdaemon by listening to DBus signals. Then it started to grow, attempting to estimate the time needed for Ubuntu One to complete the operations.

Basically it looked like this:

/galleries/dropbox/ubuntuone-indicator-synchronizing.png

Earlier this week I decided that I need to get some real-world experience with Vala and since I have found the python-based indicator to consume about 40Mb of residential memory I decided to rewrite the indicator completely.

A couple of days and bug reports later…

/galleries/dropbox/precise-indicator-1.png

Well, not much different, added some menu entries, but let’s add the file.

/galleries/dropbox/precise-indicator-2.png

Yes, finally, it calculates the current transfer rate and provides the ETA for the whole queue to be completed. It takes into account only Upload and Download processes. Since Ubuntu One has greately improved the metadata processing speed, metadata operations can be almost neglected.

However at the moment Downloads are not estimated properly since SyncDaemon does not provide size info on Downloads, bugreport pending.

The 1.0.0 version is available in ppa:rye/ubuntuone-extras, for precise the package was renamed to indicator-ubuntuone to be in line with other packages. Installing transitional ubuntuone-indicator package will install indicator-ubuntuone, so don’t be alarmed.

The project page was renamed to indicator-ubuntuone too, “one-indicator” was a weird name, really.

The new indicator installs an autostart file to /etc/xdg/autostart so it should now be launched automatically. Old per-user autostart file can be safely removed, by default it is at ~/.config/autostart/ubuntuone-indicator.desktop). For those who are interested, the compiled binary is located at /usr/lib/indicator-ubuntuone/indicator-ubuntuone.

This is a call for testing. The upcoming 1.0.2 version contains the estimation process described above and if you have some spare time please help me testing it.

Please report the bugs you may find via Launchpad bug tracker and if you’d like to help translating it to your native language, head over to Launchpad translations.

A few notes on Upstart

Upstart is an event-based replacement for the /sbin/init daemon which handles starting of tasks and services during boot, stopping them during shutdown and supervising them while the system is running.

—Upstart Cookbook upstart.ubuntu.com/cookbook

Upstart scripts have always seemed to be weird to me, somebody who learned about SysV init subsystem in Mandrake and Slackware long time ago. It seemed like Upstart was lacking lot of features but it turns out I just needed to understand what I was looking for.

So, when I found a need of a startup script, I decided to stop treating upstart as magic and here are my Upstart examples.

  • Respawning a dead daemon.

  • Monitoring the respawn limit.

  • Disable an Upstart task.

  • Listing, starting, stopping and restarting Upstart jobs.

Respawning a dead daemon

To stream files to my XBox (yes, I admit I have an XBox 360 console) I am using uShare, an outstanding piece of software that is actually compatible with Microsoft’s horrible DLNA specification. (That’s also the reason why I am so passionate about 973295 and 880076)

The default startup script simply launches the daemon as root and does nothing to keep it alive. As I found out one can make uShare exit by sending too much requests to reload the contents via its web server (this resulted from a bug in my inotify monitoring script, though). How do we ask upstart to restart the daemon?

# uShare UPnP A/V &amp; DLNA Media Server

description     "uShare UPnP A/V & DLNA Media Server"
author          "Roman Yepishev <rtg@rtg.in.ua>"

start on filesystem
stop on runlevel [016]

respawn

setuid nobody
setgid nogroup

exec /usr/bin/ushare

Original script reads $USHARE_OPTIONS from /etc/default/ushare which does not actually exist so I left this out.

What we have above is a simple script that:

  1. Starts uShare when filesystem is available.

  2. Stops uShare when system is rebooted or shut down.

  3. Respawns the process if it exits.

  4. Makes the process run as nobody:nogroup because I don’t want it to run as root.

$ sudo start ushare
ushare start/running, process 5892
$ sudo kill 5892
$ sudo status ushare
ushare start/running, process 7800

Yep, it works as expected. respawn stanza (that’s how these directives are called in Upstart) by default have a respawn limit 10 5 – 10 respawns per 5 seconds. If the application respawns faster than that (basically meaning that it cannot start successfully), the init will say

init: ushare respawning too fast, stopped

While respawn limit can be made unlimited such rate of failure signals about a real problem.

Please note that in order to control the respawn limit, you need to provide both respawn and respawn limit stanzas. respawn limit does not enable respawn:

respawn
respawn limit 10 5

Monitoring the respawn limit because we can

uShare crashing is not such a big deal but it was still upsetting my wife since it meant I had to log into the server and start the process again (before I fixed a bug in my script). But then I thought that notifying an administrator about such kind of an issue is a good thing.

# upstart-respawn-monitor.conf

description "Notify root about ushare respawn limit reached"
author "Roman Yepishev <rtg@rtg.in.ua>"

# This is a short-lived job
task

start on stopped ushare PROCESS=respawn

script
    echo "uShare reached respawn limit" | mail -s "uShared crashed" root
end script

This is another type of Upstream job, a task. It does not keep running forever and once it has finished it will not be respawned. Same thing as setting up the hostname. But what we just did is we created a simple monitoring task that will be executed once ushare reaches stopped state and a special PROCESS variable will have respawn as the reason why the service stopped. And this is all was done using Upstart only.

Before you start implementing monitoring this way, check whether there are existing solutions already.

Disable Upstart task

By default when you install a service in Ubuntu it will be immediately started. Sometimes, however, you might want to start service manually. Upstart has a concept of overrides that basically let you override any stanza in the original job file by creating a job.override file in /etc/init and placing the stanzas here.

For example, I am using LXC for some machines now and these lack tty[2..6]. Actually I don’t need these but getty keeps trying to start on these ttys. It starts and stops pretty slowly so it is not caught by the respawn limit. Disabling a task in Upstart is trivial, you just need to add manual to the stanzas:

# /etc/init/tty2.override
manual

Yes, it is that easy. Another example when you’d want to use an override file is when you want to use different options on the exec line (you will copy the original exec line and change the options then) or change the start on/stop on conditions.

Starting, stopping and restarting

If the job was converted to upstart, then interacting with it is easy:

# Getting the info about particular job:
$ sudo status cups
cups start/running, process 1503

# Getting the info about all the jobs
$ sudo initctl list
avahi-daemon start/running, process 1526
cgroup-lite start/running
mountall-net stop/waiting
nmbd start/running, process 1649
qemu-kvm start/running
...

# Stopping a job
$ sudo stop cups
cups stop/waiting

# Starting a job
$ sudo start cups
cups start/running, process 7870

# Ask the job to reload the configuration (SIGHUP)
$ sudo reload ushare

For SysV compatibility, the packages that were converted to upstart ship the symlinks pointing from /etc/init.d/something to /lib/init/upstart-job.

When you run e.g. /etc/init.d/cups restart you will receive an explanation how can you run the upstart job without the compatibility layer:

Rather than invoking init scripts through /etc/init.d, use the service(8)
utility, e.g. service cups restart

Since the script you are attempting to invoke has been converted to an
Upstart job, you may also use the stop(8) and then start(8) utilities,
e.g. stop cups ; start cups. The restart(8) utility is also available.
cups stop/waiting
cups start/running, process 4028

Cookbook

The Upstart cookbook may look like it is an unnecessary long document but once you start reading it you realise the potential of upstart. I did not want to learn about upstart until I found myself in a need of a startup script that could launch and control my daemon, the whole script ended up having 7 stanzas and I did not even need to handle forking, respawning and privilege dropping in the daemon itself.

Seriously, if you are in doubt, read the Upstart Cookbook. Have fun!