понедельник, 20 августа 2018 г.

Покупка билетов для путешествий. Обновление.

Решил обновить немного лайфхак как я покупаю дешёвые билеты. Поменялся инструментарий несколько раз - skypicker стал kiwi и испортился, skyscanner Остаётся надёжным, туры тоже бывают ничего.

Для начал определяем куда хочется хотябы примерно. На skyscanner.com пишу из LED (Пулково) в Везде (там можно выбрать такую опцию в поле куда) или конкретную страну. даже если вы хотите в определённый город лучше глянуть на страну в целом куда и за сколько можно полететь какими маршрутами.

Если сроки не определены то выбираю месяц целиком и по нему уже смотрю когда дешевле, попадают ли дешёвые билеты в мои желаемые сроки. Когда выбираете дату перелёта туда бывает что меняются и обратные перелёты - это потому что авиакомпании частенько ставят борты по расписанию и дешевле лететь обратно одной и той же компанией, с другой стороны в другой день может быть дешевле Туда а вот обратно уже выйдет дороже потому что поменялся перевозчик и его рейс по расписанию обратно летит в другой день. Таким образом удобнее всего покликать на разные дни перелёта Туда и по-прикидывать какой вариант с Обратно дешевле.



Далее я обычно смотрю есть ли прямые рейсы, если они есть и недорогие - то стоит их и принять за условный выбор и глянуть на альтернативу, если прямых нет или они дороги, тем более стоит поискать альтернативные варианты.
  • Тур. Я использую sletat.ru, большинство тур операторов к которым вы пойдёте использует его же. Старайтесь не попадаться на удочку самых дешёвых туров - если в разные отели это одна и таже кампания - скорее всего она по каким-то причинам дэмпингует, например составила перелёт из лоукостеров через непонятные аэропорты в 4 часа ночи или договорилась с отелем поселить вас в хостеле по соседству но под тем же именем что и отель. Тур полезно еще смотреть для определения есть ли чартеры - если в туре чартер (это как правило прямой рейс которых может не быть в регулярных маршрутах) то бывает суммарно тур может быть очень выгодным - присмотритесь. Есдт в Туре лоу костер или условный аэрофлот - посмотрите сами отели и перелёты - может выйти дешевле
  • Вылет из Финляндии (так и пишем в skyscanner.com  Из:Финляндия, В:везде или конкретная страна). В финляндию можло либо на своей машине, либо маршруткой, либо на пароме.
  • Вылет из Эстонии, Латвии, Литвы. Скорее всего из Литвы будет самый дешёвый, но и ехать в Вильнюс около 11 часов. Подумайте надо ли вам это (определённая романтика есть :))
  • Вылет из Москвы. Сейчас уже менее явный вариант поскольку всё больше рейсов вводится из нового Пулково. Однако тоже стоит рассмотреть тем более что перелёты из Питера в Москву и обратно за последнее время сильно подешевели и испытывают конкуренцию со стороны Сапсана
Если всё вышеперечисленное перепробовано но явно дешевле ничего нет (нужно учитывать несомненно что если из Вильнюса дешевле то вы ещё потратитесь на бензин, страховку на авто и тому подобное). То есть ещё один интересный вариант.

Перебирая различные перелёты имеет смысл посмотреть через что летят непрямые рейсы. Париж - Шарль де голь, Мадрид, Франкфурт, Копенгаген, Амстердам, Стокгольм и так далее. Потом следует запустить поиск Из: Пулково В:везде и глянуть какие из стран пересадок дешевле. Например может оказаться что куда-то на Канары например можно попасть через Италию а в италию из Питера очень недорого можно прилететь в Милан, что чаще оказывается лоукостерным терминалом Бергамо. Выбираем самые интересные даты и затем запускаем поиск Из: Милан(все аэропорты) В:страна (страна в которую хотите) Очень часто может оказаться что прямого рейса нет но если задержаться на день или вылетать из аэропорта поблизости (например прилететь в Лондонский Хитроу а вылетать и Станстед) то это будет самый бюджетный вариант. Тут дело даже не в том, что нужно потратиться на отель в месте пересадки, в конце концов это может быть интересно, а даже в том что утомительный многочасовой перелёт с пересадкой съедает у вас по-сути целый день и превращает маршрут в желаемую страну в мучение а прилетев в один город, отдохнуть там и перелететь в другой, мало того что интересно, ещё и намного приятнее и содержит в себе меньше стрессов.

Про kiwi.com - очень неплохо проект начинался но сейчас настолько сложный что я как требовательный искатель путешествий вешаю свой компьютер за несколько поисков. На данный момент быстрее и надёжнее запустить с десяток вкладок с skyscanner.com и сверять что и как выгоднее

Отели обычно ищу на booking.com, однако бывает что и неплохие варианты есть в виде частных квартир на homeaway и airbnb. Есть ещё вариант - искать самому на локальных сайтах недвижимости - их можно найти поискав имя города и tourist portal - обычно на туристических порталах определённых мест есть ссылки либо на отели местечкового масштаба либо на локальный сайт бронирований.

Если мне интереснее по стоимости Тур то отель из тура я проверяю по booking.com и по tripadvisor (просто наберите в google - имя отеля tripadvisor), нередко самые интересные предложения по цене содержат в себе немало сюрпризов неприятного характера (сеть отелей с фото самого престижного корпуса хотя селя всех в самый старый, фото самого города назначения а не отеля, промо комната которая смотрит в бетонную стену или трассу или пустырь с мусором). Будьте внимательны или платите посредникам тут уж каждый решает для себя сам. Турагенты-посредники могут быть тоже неплохи, просто нужно понимать что если вы платите людям деньги за то что можно сделать и самому - вы не должны ничего делать сами. Как вариант - выпуск визы, если я делаю через посредника, то я не отвечаю ни за какие документы - посредник сам говорит что нужно, помогает заполнить и следит чтобы всё было правильно.



вторник, 20 июня 2017 г.

SSRS 2016 Mobile Report Publisher Error 500

Hi All,

So In case you struggle as I was with SQL Server 2016 Reporting Services and specifically I had two issues:

  • SRS website simply will not show any content which I ignored at start with some similar 500 Error
  • Then when I tried to use Mobile Report Publisher I saw this 500 error

In the SRS logs ("C:\Program Files\Microsoft SQL Server\MSRS13.MSSQLSERVER\Reporting Services\LogFiles" in my case) I can see something like that

Microsoft.ReportingServices.Portal.WebHost!reportserverwebapp!fe!06/20/2017-12:13:09:: e ERROR: [frrma4f2]: OData exception occurred: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentOutOfRangeException: The UTC time represented when the offset is applied must be between year 0 and 10,000.

Now you have to remeber words OData and the string about UTC time.

Turned out the issue is with the fact that... wait for it... your server is living east of London :)

Reset timezone to EST (GMT with minus "-", to the left, west side :)) and the error is gone

I mean, Microsoft, really? :)

I was able to find a solution from this blog post
https://morgansimonsen.com/2015/12/07/office-365-hybrid-configuration-wizard-fails-due-to-datetime-minvalue-issue/
Which is about a problem in C# reported here, a problem known in 2012!!!

Hope this helps someone else out there :)

четверг, 9 марта 2017 г.

Ghost in the Shell movie

Hi All,

Just wanted to drop a post about upcoming Ghost In The Shell movie. I'm a huge fan of this idea and this future universe that Masamune Shirow created in his manga.

Fans of this universe often critisize the movie for the fact that they changed a lot and everyone is afaid that it may look like robogirl :) rather than full-cyborg "who am I?" questioning super-skilled hacker major from the manga. However I found some easter eggs which makes me beleive the movie is going to be AWESOME :)))

First, I'm sure nobody noticed, but when she "goes in" to the battle scene during the meeting involving robo geishas, she shoots the first attacker, but he is the cyborg too, so he manages to shoot Major too, in the arm - that's why later in the trailer we see her back in hanka probably repairing herself from wounds

You can even see in some later TV spots this wound (extremely interesting that it's bleeding - wow, creepy)


Also check that she is targeting geishas head, yes, this in in order to kill the hacker who may still "be there"

So ther story as you probably know is around Kuze, first of all I like how he looks like Anakin Skywalker in this shot :) so cool

So Kuze was this named-brother of Major when they were young kids - only persons survived in a plan crash. That's why they are so unique and "first of your kind" - technology for cyberbody is arond in the future, but nobody wants to put a child in the cyber-body - because this could mean dangerous consequences for human nature of his/her mind. But these two lost everyone and they required huge cyber-body replacements, that's why someone decided to try and go full cyborg with them. That is why major is unique, not because she had some super-improved cyber body (although I'm sure she has because works for the government). You can even get a glimse on this story, you can clearly see two child hands in this shot

Then Kuze dicided that is unfair that they can have a cyborg body while other people without Obamacare :)) cannot, so he decided he will donate his cyberbrain to host ghosts of others and many of his followers did the same - this is what is happeningn on a scene with many people sitting in circle connected to the network, also this is probably what is happening here

I think it's probably hard to host someones ghost, someones identity, so probably these monks are trainning to do that

So in a nuthsell Kuze's idea is to kill everyone, while hosting people without cyber-bodies in his and his followers' brains - this will mean that people will stay only in their virtual computer forms - in the network as ghosts, everyone will be a cyber ghost and everyone will have same rights and capabilities. So some kind of cyber anarchy/communism :)

I like this shot a LOT, you can see how some other people are living (I'm not sure you can fully "live" actually in this form) in the network while someone is HACKING A MAJOR'S BODY

I think this frame should set the tone for the movie - it's super creepy and awesome :) and very unique :)

It's also cool how they found a paradigm for someone to get into the network, in the original movie it's looks almost the same but from first point perspective and they figured out how to show it 3rd person, so cool

It's like diving in a pool of information (what an analogy, great job guys!) backwards while laying on a table.

Now I cannot' think of why after seeing this you can think movie is going to be bad. I'm not even mentioning the level of details in costumes and scenes, in everything. I think the movie is going to be super cool :)


четверг, 16 июня 2016 г.

Used Cell Phone Orchestration project

Hi,

I have also a project aimed at developing a low-cost device that can be programmed to perform macroses with your old used cell phone with buttons. Using clever set of MOSFETS it can "press" any button on your phone. I'm goign to use this for High-Altitude Balloon project - to reduce costs of tracking payload to a minimum: you don't need GPS, you don't need radio, you don't need any expensive parts in your payload AS WELL as in your ground station - just a phone that can accept emails and SMS/MMS texts.

Here is the project on hackaday.io https://hackaday.io/project/10130-used-cell-phone-orchestration 

I've published a new Log to the project, which tells about latest soldered and connected tests. Here is a video of what you can do with this device:


четверг, 24 марта 2016 г.

Windows Server 2016 TP4 Hyper-V Container fails to start with 80070002

So,

I was playing with new Windows Server containers feature the other day and for some reason Hyper-V container didn't want to start with the following error:

start-container : 'sg-cnt1' failed to start.
'sg-cnt1' failed to initialize: The system cannot find the file specified. (0x80070002).

It took some time and with help of Process Explorer I was able to conclude that WindowsServerCore image, which container host downloads, doesn't contain the template virtual drive (SystemTemplate.vhdx). You can check that NanoServer image does have the template, but not the full windows container image.

You might ask why I don't use a default (non-hyperv) containers? Well, because Microsoft has a bug and you cannot change container computer name - it will change the computer name of the host machine instead. That's why I was trying Hyper-V containers, from breif Nano container examitation I found that this type of container doesn't have this bug. Unfortunately I cannot use the Nano because I need to install some software and on Nano it's going to be difficult.

Solution:

Don't know. I need to find a correct SystemTemplate.vhdx somewhere. I'll update the post when I find.

понедельник, 29 февраля 2016 г.

среда, 24 февраля 2016 г.

Raspberry Pi Zero Qwerty 40 Hat for Adafruit Hackaday contest

Participating in Adafruit and Hackaday contest about Raspberry Pi Zero. I've proposed somewhat really interesting - a pocket-sized device that can be used on the go to program Arduinos and do a lot of other cool stuff.

https://hackaday.io/project/9582-pi-zero-arduino-programming-station

What you normally don't have in your pocket, but that is absolutely essential for good programming experience is a qwerty keyboard. So I decided to do a Raspberry Pi Zero hat with 40 keys qwerty and headers for directly attaching Arduino Serial connection.

As a monitor you can use your smartphone (with VNC or SSH app) connected via USB or some SPI OLED display connected right to the hat itself.

The project is so much more than just arduinos, but it really requires a lot of time.


суббота, 5 декабря 2015 г.

Convenient free parking near Helsinki Vantaa Airport. Бесплатная парковка рядом с Аэропортом Хльсинки

Hi,

Wanted to go on vacation for a month and such a long period could be pricey with airport parking, both provided by airport itself and independent one(which has a shuttle bus), cost more than 100 EUR. So I wanted to find a free parking nearby. Luckily I found one, it's Eureka's parking in Tikkurila. It's very big, almost always has a space, absolutely free and very conveniently situated - just a short walk to a Tikkurila Train/Metro station. Then it's just 3 stops with 'I' train and you are there, in the airport, currently train station is outside of the terminal, but this will change and they have a free shuttle bus to the Terminal,

Here's a link to the place on GoogleMaps

Привет, хотел полететь через Хельсинки в отпуск, на месяц, и парковка выходила дороже 100 Евро. Но я нашёл бесплатную и удобную парковку совсем рядом с аэропортом. Это парковка Эврики (ссылка есть выше), там много места, она полностью бесплатная и от неё 5-10 минут пешком до станции Тиккурила от которой идёт поезд I прямо в терминал. Понятно что с чемоданами тащиться через город неудобно, поэтому я делал так: подъезжаем непосредственно к платформе (ссылка на парковку рядом с платформой), разгружаемся, отвозим машину к Эврике и водитель пешком налегке идёт к станции.

О самом путешествии на месяц в Испанию с детьми расскажу попозже.

четверг, 19 ноября 2015 г.

SCOM PowerShell porn

Hi,

Just wanted to share with everyone some PowerShell craziness I used to analyze management pack full of overrides. This command will process all overrides in a specified Management Pack(s) and will show the corresponding Rule/Monitor ID and Display name, Rule/Monitor enabled state, display name for the context of the override, override parameter/property and its value. This thing can process any override, no matter which type - Monitor Property, Monitor Configuration, Rule Property or Rule Configuration. You can add export-csv instead of the last select to put everything in the nice spreadsheet.

Get-ScomOverride | ? {$_.Identifier -like "*Veeam.overrides*"} | Select name, @{n='Rule';e={if($_.Rule){(Get-ScomRule -id $_.Rule.Id).displayname}else{(Get-ScomMonitor -id $_.Monitor.Id).displayname}}}, @{n='RuleID';e={if($_.Rule){(Get-ScomRule -id $_.Rule.Id).name}else{(Get-ScomMonitor -id $_.Monitor.Id).name}}}, @{n='RuleEnabled';e={if($_.Rule){(Get-ScomRule -id $_.Rule.Id).Enabled}else{(Get-ScomMonitor -id $_.Monitor.Id).Enabled}}}, @{n='Context2';e={if($_.Context){(Get-ScomClass -id $_.Context.Id).displayname}}}, @{n='PropPar';e={if($_.Property){$_.Property}else{$_.Parameter}}}, Value | Sort RuleEnabled, Rule | Select Rule, RuleEnabled, PropPar, Value

пятница, 26 июня 2015 г.

Remove specific data from XML with PowerShell. Records from SCOM Default User MP for example

Hi,

Just to save for myself too. I was playing with XML support in PowerShell and was able to use the following to delete part of the XML. This is very useful, especialy for dealing with Operations Manager Default User Management Pack. You can select data for a specific Management Pack and delete it, so that the desired Management pack can be removed without deleting the Default User MP.
$xml = [xml](Get-Content ".\Microsoft.SystemCenter.OperationsManager.DefaultUser.xml")
$xml.ManagementPack.Monitoring.Overrides.MonitorPropertyOverride | ? {$_.Monitor -like "*Exchange*" -or $_.Context -like "*Exchange*"} | % {$_.ParentNode.RemoveChild($_)}
You can also export these contents before deleting. Like that
$xml.ManagementPack.Monitoring.Overrides.MonitorPropertyOverride | ? {$_.Monitor -like "*Exchange*" -or $_.Context -like "*Exchange*"} | % {$_.OuterXML} | Out-File .\MPO.xml

 To save the update MP, use Save method:
$xml.Save("FullPath")

четверг, 12 марта 2015 г.

Win8 WiFi "limited" issue and old DLink router



Hi,

You all probably already saw a lot of different fixes for the "limited" WiFi in Windows 8. TCP/IP stack reinstallations, WiFi network re-adding and many more. Well, they didn't work for me.

The reason for my troubles was DHCP from my old Dlink router. For some reasons when my router were allocating addresses dynamically with pre-set lease time, my Win8 devices were loosing connection from time to time and WiFi state were switching to "limited" state. A workaround was to restart the router, this worked for me, but then I decided to understand the source of the problem.

It turned out that DHCP renew command didn't work. My thought is that my old router has its own internal sense of current date, time and timezone :) I didn't need to fix that because my router is not a time source. And I think what is happening is that the router had it's own sense of lease time and its own sense of when IP address is expired or not, probably this doesn't work well with Windows 8.

To fix that I've added fixed, static DHCP mapping for Windows 8 devices and it worked! Now I don't have issues with Windows8 WiFi devices and I don't need to change my router (originally I thought it's a bug in the firmware and due to my router being too old I thought I had to change it)

пятница, 23 января 2015 г.

Отчётность ПФР, ФСС, Налоговая в XML (электронном) формате

С недавних пор контролирующие органы делают упор на предоставление отчётности в электронном виде.

Для многих специалистов пользовавшихся "бумажным" вариантом, переход на электронную отчётность может превратится в настоящий кошмар #спасибородинезаэто. Контролирующие органы разные, их немало, отчётность везде разная и если раньше можно было найти стандартные формы которые можно было научится заполнять и делать это каждый отчётный период то с электронной отчётностью эти формы как правило не работают.

Заблуждение Первое. Стандартную Форму можно сохранить и отправить в XML формате. Это в большинстве случаев не правда. В большинстве случаев стандартная форма распространяется в виде Word или Excel файла, при сохранении в формате XML, сам документ сохраняется в XML, то есть все параметры таблицы если это Excel и все ширины страниц и формы шрифта, если это Word. В то время как для отчётности в формате XML, это формат должен содержать только отчётность только цифры и ничего больше. Причём это должно быть в специальном формате, который "понимают" электронные сервисы контролирующих органов.

Заблуждение Второе. Без 1С или другой дорогостоящей платформы электронную отчётность не сформировать и не выгрузить. Тоже не правда и тут мы приступаем к "соли" моего поста - любой (требуется проверка, я знаю о ФСС, ПФР и Налоговой) контролирующий орган имеет в общей доступности бесплатное приложение для формирования отчётности в электронном формате.

Теперь по порядку:

Налоговая (nalog.ru)
Приложение Налогоплательщик ЮЛ http://nalog.ru/rn78/program/all/nal_ul/
Оставляет достаточно приятные впечатления, удобно устанавливается, достаточно интуитивное управление и создание документов. Если не знаете с чего начать рекомендую в меню Документы выбрать "Ввод с помощью мастера документов"

Далее нужно заполнить все необходимые данные о налогоплательщике двигаясь по удобно сформированным шагам

На 6 шаге нужно заполнить саму декларацию, то что требует заполнения выделяется зелёным фоном.

Некоторые абзацы отчёта могут быть заполнены но не включены, их нужно включить чтобы они появились в выгрузке
Если какой-то из разделов отсутствует (серый), его нужно добавить. Кроме того рекомендую периодически нажимать на иконку с буквой Р или клавишу F5 чтобы те поля которые высчитываются - посчитались.

Когда документ заполнен нужно нажать на иконку с буквой К и таким образом проверить что ошибок нет. Далее можно сохранять документ и в последнем шаге мастера выгружать в XML формате пригодном для отправки электронной отчётности.

ФСС (fss.ru)
АРМ Подготовка отчётов для ФСС http://fss.ru/ru/fund/download/55818/index.shtml
Скачиваем первый файл вверху страницы, установка не такая интуитивная, необходимо запускать с правами администратора (правой кнопкой мыши -> запуск от имени Администратора). В процессе установки программа будет скачивать базу адресов.

В самой программе необходимо для начала перейти в раздел Справочники и Добавить Страхователя и при необходимости физических лиц или мед учреждения

Затем необходимо перейти в меню "Учётная работа" и выбрать необходимую форму, затем нажать иконку Вставить

Дальше необходимо заполнить форму, к сожалению не так всё очевидно как в налоговой программе по-этому я подразумеваю что вы в курсе как заполнять формы для ФСС, и в конце выбрать иконку "Выгрузить XML", в результате сформируется XML файл который можно использовать для предоставления электронной отчётности
ПФР (pfrf.ru)
Методом проб и ошибок а также научного тыка выбрана программа Spu_orb разработанная в Оренбурге http://www.pfrf.ru/branches/orenburg/info/~rabot/program
Установка и использование довольно интуитивны и понятны. Позже напишу поподробнее.

Будет апдейт.

вторник, 20 января 2015 г.

Incorrectly flashed atmega328p back to life

Hi,

I'm new to microprocessor programming and all the related stuff (bootloaders, fuses, ISPs, etc.), so I faced a newbee issue.

Symptom:

I was trying to flash atmega328P with bootloader that will suport 8MHz internal clock (so that I don't need an external oscillator) and can be futher optimized in terms of power consumption. I did everything correctly in terms of wiring USBasp programmer (I was using the following instructable), but then unintentionally (I just knew that LilyPad bootloader would also work) I programmed LilyPad's bootloader which also means LilyPad's fuses, which also means (as I later discovered) usage of external oscillator (nice tool to decode fuses).

So, that brought me all the way to "Yikes invalid signature 000000" with usage of -F option in avrdude, or "avrdude: error: programm enable: target doesn't answer. 1" without it. Different "-B" options (-B250, -B5, etc.) didn't work for me. Chip is just completely silent.

And also "avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xfc" when I try to talk to the MCU via Serial ports with help of FTDI chip. At least I could see that chip is not dead comletely, it's replying something. Probably abrakadabra and maybe it could be decoded by using a proper avrdude settings, but I tried different baud rates and other settings and nothing worked.

Cause:

MCU just expect an external clock source and just doing nothing without it.

Resolution:

Connect an oscillator. But what if you don't have a spare one? Do it like me:


This is a wireless NRF24L01 board and it has an oscillator on it, just connect board ground (yellow on the photo and PIN1 on this wireless board) to your MCU ground and oscillator lines (green and white) to PIN9 and PIN10 on your atmega328P.

This fixed everything for me, Chip is alive and I can see all fuses, so I was able to reprogram them.

Although it's a little bit ackward - because oscillator is 16Mhz and LilyPad bootloader expects 8Mhz.

Hopefully this post will save some time for someone who faced the same issue.

UPDATE:
Looks like this is only a one part of the puzzle, the other one is protocol issue which I also mentioned above, it is still present after a correct bootloader is flashed.

Apparently the issue is with not very accurate internal oscillator - it just doesn't work with high baud rates for programming. There is a very good and detailed explanation on how to fix this by re-compiling a bootloader to use slower upload speed, I do not have necessary tools to do that, so I do think I'm going to do that, I think for me it's OK to load firmware via the ISP


I was able to confirm that it's working and chip is perfoming properly using its internal oscillator. Then I can install a code that will programmaticaly set slower baud rate if I need to talk to the firmware onboard the atmega chip.

пятница, 16 января 2015 г.

Netgear Stora with connected Arduino and Zabbix

Was able to install Zabbix on my Netgear Stora device. Took some time and setup code modifications were required (because mysql is lower version in Stora as well as some php addons).

Zabbix is very usefull tool to quickly configure the monitoring and notification system with ability to check metric charts and trends and set triggers and actions.

I'm using it now to monitor the free space and overall health of the Netgear Stora device, router traffic (via SNMP) and, what is more important for me - different aspects of Arduino subsystem (I have Arduino Due connected via USB). I've created a PHP script which takes commands as parameters and returns data reported by arduino. Zabbix agent is using this script to get data from Arduino. Currently I monitor RAM usage of my Arduino system (because has a dynamic tree-like memory allocation system for data reported by remote nodes), so that I can see if my Arduino is about to kaboom :) because of too many nodes reporting to the root node or just because of firmware glitch on Arduino, illumination using the photoresistor on one of the nodes (just for testing purposes), here is the chart screenshot


Also I'm collecting number of cycles certain node is unresponsive, so that zabbix can notify me if certain node is not responding anymore. I have plans to use Zabbix way of autodiscovering new nodes and automatically monitoring them, currently I've just added 2 active node manually, here is the configuration of the Zabbix item, Arduino RAM usage in this case.


Below is a config of my zabbix agent. It should be placed as a separate .conf file into zabbix_agentd.conf.d subfolder, but before that you have to uncomment the following line in the main agentd config:

Include=/opt/usr/local/etc/zabbix_agentd.conf.d/*.conf

userparameter_arduino.conf:

UserParameter=arduino.light,/opt/bin/php -f /home/sg_parser/ardu_get.php l 1 3
UserParameter=arduino.ram,/opt/bin/php -f /home/sg_parser/ardu_get.php s 0 3
UserParameter=arduino.cycles[*],/opt/bin/php -f /home/sg_parser/ardu_get.php c $1 3

All of the paramters for ardu_get.php is just to extract the numeric part of certain node, light sensor is on the node 1 for example, while RAM is on the parent or 0 node and cycles can be gathered for any discovered node.

And now non-arduino part of using Zabbix, here is free space on my Stora, Stora CPU usage and traffic via router (using SNMP data). I'm also monitoring mysql load and apache performance.



вторник, 11 ноября 2014 г.

Uploading Arduino .hex from Netgear Stora

AAAAAAAAA

I've done it. After so much pain. I even do not remmeber all the steps. However:


  • I've compiled usb drivers and ftdi drivers. I have a post about it 
  • I've compiled avrdude 6 on my Netgear Stora. Don't ask how. There was also a lot of pain. But for some reason avrdude 6 worked while v5 still cannot be compiled.
  • I have a daemon which talks to arduino, so to program I have to switch it off
  • Then I faced an issue whatever I tried I receive "avrdude: stk500_getsync(): not in sync". Looks like the issue was with my usb and ftdi drivers - for some reasons they can't help avrdude to negotiate a correct baudrate for my arduino. I tried several and looks like 57600 worked for me. I tried terminal mode like this
/root/avrdude-6.0.1/avrdude -t -v -v -v -v -c arduino -p m328p -b 57600 -P /dev/ttyUSB0

  • But then another issue arised - looks like core version of avrdude cannot properly reset the arduino. There are several tricks on how to do that manually - I'll try them later. Also I think Arduino's version of avrdude can do that, but I have issues compiling it on my Netgear (some Perl issues - nothing too serious can be solved in the future). So I went with another solution - I just reset my USB subsystem and then attach to arduino to upload a sketch. To reset the usb subsistem I'm doing the following:

echo -n "1-0:1.0" > /sys/bus/usb/drivers/hub/unbind
echo -n "1-0:1.0" > /sys/bus/usb/drivers/hub/bind

  •  In the above code IDs of your USB hub could be different, so check them in the folder /sys/bus/usb/drivers/hub/, but I guess on all Storas they should be the same.
  • Then upload the sketch, like that:
/root/avrdude-6.0.1/avrdude -v -v -v -v -c arduino -p m328p -b 57600 -P /dev/ttyUSB0 -D -Uflash:w:/home/arduino/Firmw4_4.cpp.hex
Have a good time with your IoT ;)

среда, 24 сентября 2014 г.

Low power wireless sensor node, using stock arduino

Hi ardu-people,
There are a lot of posts in the Internet about making a low power arduino projects. However most of them assume you have to do it with custom built arduinos using atmega chips, I think it’s a correct approach, BUT it is still possible to do a low power node even on stock parts. Below are some hacks I discovered or confirmed while creating my low power projects.
  • LED lights
    There are a lot of articles about how much power do they really consume and I can only confirm that, even this tiny power led on your Pro Mini or Nano. I used sharp knife to cut the connection to the power led on my Pro Mini and I desoldered leds on all other peripherals such as radio power converter
  • Power down mode
    For my arduino I was using Narcoleptic library, and PowerDown mode for the nrf24l01 radio. For arduino everything worked perfectly, for radio see below
  • Cut power to peripheral devices
    To save some more power we can disable sensors while arduino and radio are sleeping, simple solution is to power up sensors using arduino pins, set pin to HIGH to enable device, LOW to power it down, this worked perfectly for me. If you see issues with measurements, you may need to add a delay after powering a sensor up. More appropriate solution is to use tip120 or something similar to disable/enable power for all sensors at once.
  • Radio nrf24l01 power down issues
    Unfortunately looks like Nfr chip doesn’t like power manipulations, after several cycles of powering it down with arduino pin as a power source as per above while radio is in the powerdown mode, the radio developed some kind of a power leak and started to consume more (~6ma). Radio is functioning properly, but consuming a lot for a sleep period. I’ve understood that it’s consuming power via MOSI line (pin11), the solution was to set all nrf pins to low and to switch MOSI pin to input mode, don’t forget to switch it back to output when powering everything back up.
Stay tuned, I’ll be working with reducing power consumption with relays, coz they are eating a LOT
Written with StackEdit.

вторник, 23 сентября 2014 г.

Покупка лоукостерных билетов lifehack

Предисловие

Опишу коротко как я покупаю билеты в лоу костерах. Для начала несколько базовых тезисов которые мной проверены уже неоднократно


  • Low cost будет дешевле в 90% случаев. Много раз приходил к этому, даже с учётом оставления авто на платной парковки у аэропорта, грин карты, бензина и т.д. Конечно когда надо делать пересадки и при этом ночевать где-то и если нужно долго и неудобно добираться при этих пересадках до аэропорта, особенно если пересадок больше чем одна - то это уже звоночек чтобы посмотреть и на стандартные билеты например из Питера напрямую. Если вы молоды и с вами нет детей то ночёвка и 10ч пребывания в Лондоне с переездом из Гатвига в Станстед могут быть даже интересными, хотя врят ли :)
  • Low cost бывает не только в Финляндии. Сейчас Wizz Air набирает ход и у них очень хорошие предложения из прибалтики, кроме того можно ими очень дёшево полететь из Турку в Польшу а от туда дальше.
  • Ехать до Лаперанты ближе чем кажется. После того как построили ЗСД - то стало гораздо быстрее и комфортнее
  • Одного кабинного чемодана достаточно. Порой бывает трудно в это поверить но даже моя жена которая не может носить одно платье или купальник два дня подряд :) вполне успешно справляется (не знаю каким образом - надо у неё спросить) этим небольшим кабинным чемоданом. Если у нас бывает много покупок "домой" то можно просто купить (или заранее взять с собой) чемодан и докупить багаж к обратному билету - проверено проблем никаких (главное по весу распределить всё правильно)
  • Распечатывайте все подтверждения. Это особенно верно для авиа билетов (а точнее посадочных которые печатаются поcле того как через вебсайт вы проходите check-in), потому как их распечатка в аэропорту может обойтись ОЧЕНЬ дорого.
  • Приезжайте в аэропорт заранее. 2 часа до вылета это стандарт и неоднократно бывало что если забиваешь на это золотое правило попадаешь в неприятные ситуации. Кроме того, правда сейчас это актуально только для Wizz Air - если первым проходишь все проверки и встаёшь в очередь на посадку - можно занять более комфортные места и например занять место ребёнку если для него места не предусмотрено (это правда верно только если самолёт не забит под завязку). Ryanair изменили правила и теперь всем принудительно назначаются места просто по порядку, по-этому для них lifehack другой - регистрируйтесь в самый последний момент - например в ночь перед вылетом, тогда у вас будут места в самом хвосте и если самолёт не полный то сразу за вами будет уйма свободных мест или даже рядов.
  • Если у вас только кабинный багаж - иногда можно не стоять в очереди. В некоторых аэропортах бывают отдельные стойки Ryanair которые занимаются всем кроме регистрации - в них вы можете сделать Visa Check (вам поставят печать что ваш паспорт позволяет путешествовать дальше) и смело идти прямиком на проверку безопасности и на посадку.
  • Детская коляска не только коляска но и 15кг груза :).  Если у вас есть детская коляска да ещё и с чехлом то в неё можно запихать всё что не влезло в кабинный багаж (кстати на ребёнка с местом выделяют отдельный кабинный багаж) - обычно на это смотрят сквозь пальцы, я даже бывало скотчем памперсы и мячик прикручивал - и ничего долетели. Правда есть один негативный момент в коляске - нужно стоять в очереди в регистрацию чтобы коляску положили в багаж, хотя бывает с детьми, особенно маленькими, пропускают вне очереди
  • Разложите все жидкости в пакеты заранее и в доступном месте. Этот lifehack разработала моя жена - теперь у нас никогда не бывает никаких проблем на Security проверках - всё происходит очень оперативно и быстро.

Покупка Билетов

Сейчас я в основном пользуюсь новым и очень хорошим ресурсом skypicker.com - он отличается от остальных тем что может планировать перелёт учитывая пересадки в один или несколько дней и ему можно задавать очень гибкие условия поиска. Я делаю примерно следующее.
From: Radius search (и выбираю радиус с центром где-то в Чудском Озере, чтобы он захватывал Тампере, Турку и Вильнюс с Каунасом, но не Стокгольм (хотя такой вариант тоже возможен если паром не дорог)) (Хотя можно и просто Лапперанту выбрать)


To: Выбираете или страну куда хотите попасть или конкретный город, можно Anywhere если ещё не решили куда :)

Departure: Удобнее всего выбирать неделю от и до когда вы готовы вылететь, вот например я выбрал с 9 по 15 Ноября - я готов куда-нибудь улететь


Return: Тут удобнее всего выбрать длинну отпуска, например - я хочу отдыхать 10-15 дней (лучше выбирать -1 и +1 день от желаемого размера потому что более дешёвое предложение может не попасть хотя оно например на день больше но рано утром прилетаете - то же ведь вариант). Хотя бывает что диапазон дат тоде удобен - например если вы уже знаете с какого по какое число у вас отпуск - в departue выставляете начала отпуска -1 день, + 3-4 дня, в return выставляете дату окончания отпуска -3-4 дня, +1 день
Нажимаем Поиск.
Поскольку у меня было выбрано anywhere - мне показываются различные варианты, кроме всякой разной скандинавии я вижу Париж и Милан за 50 евро с человека, неплохо. Выбираю Милан. Кроме того можно заметить что Skypicker даёт возможность указать email и они уведомят тебя если цена упала ещё ниже, для меня правда эта функциональность почему-то не работала

Когда выбран конкретный город - skypicker даёт список дешёвых вариантов по поиску, вот самый дешёвый вариант для меня из Вильнюса в Милан за 50 евро на человека, до Вильнюса правда далековато (кстати 10-11 часов может не хватить - мы как-то нарвались на ремонт дорог в Литве и чуть не опоздали). Есть вариант из Таллина за 3300 руб на человека - тоже неплохо. Или из Лапперанты (нету на скриншоте) за 80 евро, я скорее всего выбиру Лапперанту потому что не раз уже оттуда летал и ехать недалеко, да и по слухам Эстонская таможня бывает непредсказуема

Покупка

Покупать лучше непосредственно на сайте Авиакомпании ryanair.com или wizzair.com. Уже ввести известные вам из skypicker-а даты вылета выбрать билеты и купить.

Будьте бдительны - задача лоу кост кампаний втюхать вам всё что только можно - отказываемся от страховки (No Travel Insurance), не покупайте всякие чемоданы, место я тоже считаю покупать не обязательно, если у вас только кабинный багаж - багаж обычный вам не нужен (No bags), кстати недавно лоу кост компании разрешили помимо кабинного багажа ещё иметь и небольшую сумку для фотоаппарата или ноутбука например, не ведитесь ни на какие разводки более дешёвого авто в аренду или отелей. Кроме того уже в момент ввода данных кредитки - есть возможность перейти на отдельное окошко конвертации курса и отключить конвертацию (потому что лоу костеры по своему курсу переводят евро в доллары и снимают с вас уже доллары, что как правило дороже чем если с вас снимут Евро напрямую)

Кроме того старайтесь как можно более внимательно заполнять данные о себе - имя фамилия как в пасспорте, данные пасспорта, потом менять это может выйти в копеечку.

Когда покупать?
Как правило цены у лоу костеров меняются постоянно (в зависимости от того сколько билетов уже продано). Мне удалось проследить некую закономерность для ryanair - самая низкая цена как правило за 60 или 30 дней до вылета (+/- конечно но в этот период) и как правило с пятницы по субботу, иногда если 30 или 60 дней приходится на воскресенье то например в воскресенье-понедельник. В принципе можно сказать что в одну сторону билет должен быть меньше 50 евро (это Европа за исключением Испании и Португалии и дальней Италии (Сицилия, Рим)), причём в эти вот периоды 30-60 дней, может быть значительно дешевле, вот в примере я нашёл например из лаперанты за 40(если перевести в одну сторону), но не исключено что там билет туда вообще за 20 а обратный 60 - потому что время его скидки ещё не пришло. Самое выгодное покупать билеты туда и обратно отдельно попадая в вышеуказанные коридоры скидок (но даже у меня так не всегда получается :))

P.S.

Кроме Skypicker.com ещё есть удобный skyscanner.com, он менее удобен на мой вкус но имеет больше фичей, более визуален и включает ВСЕ авиакомпании бюджетные и не только, skypicker как я понимаю заточен именно под бюджетные

суббота, 2 августа 2014 г.

Италия, около 6 дней, на машине из Милана.

Съездили на майские праздники в путешествие по северной Италии, летели из Вильнюса, там Wizzair как-то совсем недорого билеты продаёт. В Вильнюсе парковка у аэропорта наши номера не распознаёт, но немного постояв, подумав :) - открывают, бронировать можно через интернет http://www.unipark.lt/ . Ещё лайфхак по Вильнюсу - 10 и даже 11 часов из Питера может не хватить :) Ну а дальше описание маршрута, он не по дням а по перемещениям:


  1. Машина в Бергамо и до отеля в Падуе, хороший отель - это миниквартира, есть стиральная машина даже и большая общая кухня, утюг http://www.booking.com/hotel/it/b-b-brandolese.en-gb.html?sid=38ea3f5e30b3a0743c9546118c2d1539;dcid=2
  2. Венеция (тут надо отдельный пост :)), из Венеции в Верону, в Вероне тоже хороший отель, не в центре, но до центра 5 минут на машине, в Вероне красивый «Колизей» там кстати устраивают концерты классической музыки, билеты нам сказали можно купить через интернет. Ещё местный прохладительный напиток из шампанского, кампари и сока - очень освежает. Отель гардения http://www.booking.com/hotel/it/gardenia-verona.en-gb.html?sid=38ea3f5e30b3a0743c9546118c2d1539;dcid=2
  3. Из Вероны в Тоскану, в Монтекатини Терме, там жили два дня, на поезде ездили во Флоренцию (10 евро), там очень просто купить билет на поезд прямо на станции, городок маленький и там всё близко. Бесплатная парковка в Монтекатини на выезде из города
    .Отель, осторожно, не все говорят по английски Smiling face with smiling eyes http://www.booking.com/hotel/it/savoia-campana.en-gb.html?sid=38ea3f5e30b3a0743c9546118c2d1539;dcid=2
  4. Во Флоренции рекомендуем креативное пространство на втором этаже крытого рынка, мы случайно туда попали но там есть вся местная кухня и вино, готовят прямо при тебе. Местный деликатес - лампредотта - на любителя :)
  5. Из Флоренции обратно в Монтекатини, покупались в термальных бассейнах, спросили ближайший на ресепшене.
  6. Из Монтекатини на машине в Пиза, там оставили машину на улице, было воскресенье, по этому бесплатно и пошли пешком смотреть на башню, там сейчас пускают наверх, билет лучше купить сразу, там пускают по расписанию.
  7. Из Пиза в чинкве терре, там можно на машине доехать только до Леванто или Монтероссо, машину можно оставить у вокзала в Леванто, в Монтероссо прямо на пляже и на поезде поехать в Вернацца - это самый красивый городок из 4х. Только нужно очень чётко проверить расписание поездов - не все останавливаются
  8. Потом мы поехали в городок между Миланом и Бергамо - Моццо, вот отель, он очень хороший и по цене и качеству, особенно если на машине http://www.booking.com/hotel/it/bes-hotel-bergamo-west.en-gb.html?sid=38ea3f5e30b3a0743c9546118c2d1539;dcid=2
  9. Отсюда ездили в Милан и на шоппинг в бутики, самый удобный и выгодный шоппинг в serravalle, правда это немного вдалеке от самого Милана. http://www.mcarthurglen.com/it/serravalle-designer-outlet/it

вторник, 10 декабря 2013 г.

Talking to Arduino in PHP via USB in Linux

I'm really proud of myself. I was able to comeup with the solution for the problem which is being discussed in the internet a lot - how to properly talk to arduino from a PHP script, actually from any kind of script. The problem is that Arduino resets itself when you open a connection, this is not OK and most of people just apply some harware hacking to disable this behaviour. I wanted a software solution.

Also for some reasons I cannot read arduino output using "php_serial.class" code. SO, here is my alternative solution:


  • I've created a deamon which redirects arduino serial output to a log file. This daemon can be started and stopped, on re-start it will re-write the logfile. I've done this for maintenance purposes - the intention is to clean the log file periodically, so that it doesn't grow to Gigabytes which ultimately could affect the performance of the overall solution(so, not because I don't have enough storage - I'm doing this on Netgear STORA after all :)). I've created a daemon script and an init script for this daemon. The code for the daemon script is easy "cat /dev/ttyUSB0 > /home/com_log.txt &" and that's it. Init script is more complex - you have to properly remove the log file and kill the cat process. You can download the code here
  • Once I have a daemon - reading Arduino from any places without resetting it - is super easy. But you have to read last lines if you want latest output. I've created a script which sends to Arduino a command to print the updated information about temperature and humidity sensors, then the script reads new values from the log file and saves them into the MySQL database. Here is the code
  • The script above is added to the crontab to collect temperature/humidity samples every 10 minutes
  • Then I've created a page using Google's Charts JSAPI examples with chart for each counter. Code is here.
This is how it looks like (there is still some work to do with date picker, correct dates on axis, etc.)

Now my Stora is a temperature station :) and since I have relay connected to the Arduino I can adjust temperature by switching heating on or off, but this part is later... stay tuned.

BTW, here is an Arduino scetch - it's a modified version of arduino code from UberFridge project by some awesome guy.

P.S. Please forgive me for code quality - I'm doing this for myself rather than for opensource community :) If someone want to polish the code and make it available on some communities - you are absolutely free to do this, I would appreciate a link to my blog though.


понедельник, 2 декабря 2013 г.

Talking to Arduino from Netgear Stora via USB

Weeks of investigations and code compiling and finally I found that the answer is quite simple and elegant.

  • Download original(or whatever is installed in your Stora) Kernel source. Original one can be found here http://www.openstora.com/wiki/index.php?title=Source_Code
  • Extract kernel sources from stora sources.
  • (Optional - depends on compiler that you have) I had gcc from optware ipkg installation, so I had to change the Makefile - otherwise 'make menuconfig' will tell you that mixed explicit and implicit rules.
    • Locate all places where you see something like this "$somthing: something:"
    • Split each variable before colon into the separate line and duplicate code from one into the empty one.
    • Run 'make menuconfig' if there is still "mixed implicit...bla-bla-bla" error - check the line number and do the separation trick above again
  • Run 'make menuconfig'. Do no uncheck anything(you need the kernel in it original configuration) - you need to enable experimental drivers/code (because ftdi_sio is expiremental in Stora code) and then go to drivers > USB > USB serial, enable generic and core usbserial drivers as well as FTDI driver (ftdi_sio), close and save the config
  • Run 'make modules ARCH=arm'
  • Copy usbserial.ko and ftdi_sio.ko where you store other drivers.
  • I think I also added both drivers into modules.conf or whatever is the procedure for device drivers, 'depmod -a', you know... :) this kind of stuff
  • Also I did the trick with udev rules (http://playground.arduino.cc/Linux/All), but I'm not sure it was necessary.
  • Plugin the arduino board - do modprobe usbserial, ftdi_sio if necessary (if they are not loaded already) and here you go... you can talk to arduino(it was /ttyUSB0 in my case)
P.S. After everything worked I was using screen command to test everything - it works very well with my ardu. But you can find other examples(http://playground.arduino.cc/Interfacing/LinuxTTY)