<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>const&#039;s personal blog</title>
	<atom:link href="https://const.kiev.ua/feed/" rel="self" type="application/rss+xml" />
	<link>https://const.kiev.ua</link>
	<description>software and hardware</description>
	<lastBuildDate>Mon, 01 Sep 2025 08:11:05 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.11</generator>
	<item>
		<title>The AI Dopamine Pit: How &#8216;Vibe Coding&#8217; Is Slowing Me Down</title>
		<link>https://const.kiev.ua/2025/08/the-ai-dopamine-pit-how-vibe-coding-is-slowing-me-down/</link>
					<comments>https://const.kiev.ua/2025/08/the-ai-dopamine-pit-how-vibe-coding-is-slowing-me-down/#respond</comments>
		
		<dc:creator><![CDATA[const]]></dc:creator>
		<pubDate>Sun, 31 Aug 2025 12:16:53 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://const.kiev.ua/?p=588</guid>

					<description><![CDATA[I was reflecting on my workflow with AI assistants recently and caught an interesting, and slightly frustrating, pattern in my own behavior. When I treat the AI as a focused tool, giving it specific commands like &#8220;refactor this function&#8221; or &#8220;explain this error,&#8221; the process is remarkably efficient. The work flows smoothly. But sometimes, in...]]></description>
										<content:encoded><![CDATA[
<p>I was reflecting on my workflow with AI assistants recently and caught an interesting, and slightly frustrating, pattern in my own behavior.</p>



<p>When I treat the AI as a focused tool, giving it specific commands like &#8220;refactor this function&#8221; or &#8220;explain this error,&#8221; the process is remarkably efficient. The work flows smoothly. But sometimes, in an attempt to truly maximize the AI&#8217;s potential, I push it further and slip into a different mode—a pattern that the developer community has aptly named <strong>&#8220;Vibe Coding.&#8221;</strong> I&#8217;m not just asking for help; I&#8217;m trying to offload the entire architectural thought process, throwing a vague, high-level prompt at it like, &#8220;build a complete service that does X, Y, and Z.&#8221;</p>



<p>That&#8217;s when the trouble starts.</p>



<p>The other day, I did exactly that. The AI generated a plausible chunk of code, but it failed on the first run. My immediate reaction wasn&#8217;t to read the code or think about the problem; it was to copy-paste the error log right back into the prompt. &#8220;Fix this,&#8221; I commanded. It gave me a new version, which then produced a different error. This loop continued for&#8230; well, for longer than I&#8217;d like to admit.</p>



<p>At some point, it hit me: if I had just taken 20 minutes to read the original code, maybe Google a thing or two, I would have solved the problem myself and been done hours ago. Instead, I found myself stuck in what I can only describe as my personal <strong>&#8220;Dopamine Pit&#8221;</strong>—the allure of a fully-automated, AI-generated solution had trapped me in a cycle of endless, unproductive tweaks.</p>



<p>I&#8217;m writing this down mostly to unpack that feeling. It&#8217;s the strange paradox of working with AI: my ambition to make the machine save me <em>more</em> time actually ended up creating a black hole for it. It turns out there&#8217;s a fine line between effective delegation and counterproductive abdication of your own thinking, and &#8220;Vibe Coding&#8221; with an AI is a perfect way to cross it.</p>



<h3 class="wp-block-heading">Deeper Dive: The Psychology of the Dopamine Pit</h3>



<p>The most fascinating and dangerous part of this entire cycle isn&#8217;t the faulty code; it&#8217;s what happens in my brain. The &#8220;Dopamine Pit&#8221; is so effective because it exploits the path of least resistance.</p>



<p>When an error pops up, I&#8217;m at a fork in the road.</p>



<p><strong>Path A is the path of effort.</strong> It requires me to stop, engage my brain, read the error message, analyze the stack trace, load the surrounding code&#8217;s context into my working memory, and form a hypothesis. It&#8217;s real cognitive work.</p>



<p><strong>Path B is the path of instant gratification.</strong> I just copy the error and paste it into the AI prompt with the command &#8220;fix this.&#8221; It requires almost zero mental effort, and in return, I get an immediate response—a new block of code.</p>



<p>That quick, effortless response is the dopamine hit. It <em>feels</em> like progress. My brain gets a tiny reward for taking an action, even though the action was mindless. The problem is that when the AI&#8217;s &#8220;fix&#8221; inevitably fails, my brain is already primed. The easiest thing to do—the path that offers another quick hit—is to repeat the cycle.</p>



<p>Each loop pulls me deeper into the pit. I&#8217;m so focused on the low-effort cycle of prompting and pasting that I fail to see the bigger picture: the cumulative time and frustration are soaring. Escaping the pit requires a moment of mindfulness—the conscious decision to choose the initial effort of Path A over the deceptive ease of Path B.</p>



<h3 class="wp-block-heading">The Antidote: Working in Verifiable Chunks</h3>



<p>So if &#8220;Vibe Coding&#8221; with an AI is the trap, what’s the way out?</p>



<p>After falling into that dopamine pit, I realized the solution wasn&#8217;t to stop using the AI for complex problems. The solution was to change the <em>scope</em> of my requests. I needed to break down the problem not just into smaller steps, but into steps whose output I could grasp and validate in seconds.</p>



<p>I started adhering to a simple practice: <strong>working in verifiable chunks.</strong> The principle is to never ask an AI to generate more code than you can comfortably understand and verify at a glance. The goal is to keep the cognitive overhead low.</p>



<p>Let&#8217;s look at the contrast:</p>



<p><strong>A &#8220;Vibe Coding&#8221; Prompt (High Cognitive Load):</strong></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>&#8220;Build a complete user authentication service in C# using ASP.NET Core Web API. Use JWT for tokens, Entity Framework Core to connect to a PostgreSQL database, and include endpoints for registration, login, and profile updates.&#8221;</p>
</blockquote>



<p>The AI will generate a lot of code for this: multiple controllers, services, DTOs, and database context configurations. To truly verify it, you have to read every file, understand the dependency injection, check the security of the token handling, and trace the logic through multiple layers. The time you spend trying to comprehend this &#8220;instant&#8221; solution is often more than the time it would have taken to build it piece by piece yourself.</p>



<p><strong>A &#8220;Verifiable Chunk&#8221; Prompt (Low Cognitive Load):</strong></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>&#8220;Write a single, static C# method that validates password strength. It should take a string and return a boolean. The password must be at least 12 characters and contain an uppercase letter, a number, and a special character.&#8221;</p>
</blockquote>



<p>The result of this prompt is a small, isolated method. I can read it in 30 seconds. I can see immediately if the logic is sound. I can write a quick unit test for it. I am in complete control. I can then ask for the next chunk: &#8220;Now, show me how to hash a password using <code>BCrypt.Net</code>.&#8221;</p>



<p>This approach puts me back in the driver&#8217;s seat. The AI isn&#8217;t the architect; it&#8217;s a hyper-competent assistant handling the small, well-defined tasks I delegate. This is where the real time-saving happens, without the frustrating debugging loops.</p>



<h3 class="wp-block-heading">Conclusion: Staying Mindful is the Real Work</h3>



<p>My journey into the &#8220;Dopamine Pit&#8221; wasn&#8217;t really about the AI&#8217;s failures, but about a flaw in my own workflow. It revealed a subtle but powerful psychological trap that&#8217;s easy to fall into when the promise of an instant fix is just one prompt away.</p>



<p>The central lesson for me has been learning to recognize that critical moment when an error appears. The real challenge isn&#8217;t technical; it&#8217;s resisting the siren call of that low-effort dopamine hit from asking the AI to &#8220;just fix it.&#8221; When I fall for that, I&#8217;m no longer developing software; I&#8217;m just managing a frustrating, unpredictable machine.</p>



<p>The most effective defense I&#8217;ve found against this is a practical one: <strong>working in verifiable chunks.</strong> By consciously keeping my requests small enough to be immediately understood and validated, I never cede control. The AI remains a powerful assistant, not an architect I have to blindly trust and then painfully debug.</p>



<p>Ultimately, the responsibility to think remains with me. The next time an error pops up, I know I have a choice: the deceptive ease of another prompt, or the real, focused effort of understanding. Choosing the latter is how I escape the pit and get back to doing the actual work.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://const.kiev.ua/2025/08/the-ai-dopamine-pit-how-vibe-coding-is-slowing-me-down/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Meeting Github Copilot coding agent</title>
		<link>https://const.kiev.ua/2025/06/meeting-github-copilot-coding-agent/</link>
					<comments>https://const.kiev.ua/2025/06/meeting-github-copilot-coding-agent/#respond</comments>
		
		<dc:creator><![CDATA[const]]></dc:creator>
		<pubDate>Fri, 20 Jun 2025 11:14:28 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AI Pair Programming]]></category>
		<category><![CDATA[DevOps]]></category>
		<category><![CDATA[GitHub Copilot]]></category>
		<category><![CDATA[Software Development]]></category>
		<guid isPermaLink="false">https://const.kiev.ua/?p=585</guid>

					<description><![CDATA[I recently upgraded my GitHub Copilot plan to Pro+, which finally allowed me to start using the coding agent in standalone mode. It&#8217;s almost like hiring a junior programmer for $39 a month. At first glance, everything went as expected. I created several issues in my company&#8217;s private repositories (yes, you can use your private...]]></description>
										<content:encoded><![CDATA[
<p>I recently upgraded my GitHub Copilot plan to Pro+, which finally allowed me to start using the coding agent in standalone mode. It&#8217;s almost like hiring a junior programmer for $39 a month.</p>



<p>At first glance, everything went as expected. I created several issues in my company&#8217;s private repositories (yes, you can use your private Copilot in your company&#8217;s repos). Copilot began working, and within 10-15 minutes, it started reporting that everything was done and I could begin reviewing its Pull Requests.</p>



<p>That&#8217;s where the fun began. My first task was to migrate a CI build from Jenkins to GHA, meaning we needed to port a Jenkinsfile to GitHub&#8217;s workflow YAML. The first issue I noticed was that Copilot doesn&#8217;t detect failed builds. Second, it can&#8217;t read failed build logs. So, when I nudged it with a &#8216;hey, build failed&#8217; comment, it started peering into the sources and the new <code>build.yml</code>, guessing why the build might have failed. It didn&#8217;t find the root cause, but it did generate a new commit with tons of debug logs in <code>build.yml</code>.</p>



<p>I then explicitly told it what the problem with the build was and asked it to revert the last commit.</p>



<p>There were a few more build problems, but when I posted the build logs in the PR review comments, the bot quickly fixed everything. In the end, we merged the PR, and my initial experience is this: you get what you pay for – a junior programmer who constantly needs your attention, but at least you don&#8217;t have to work on boilerplate or tech debt tasks.</p>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://const.kiev.ua/2025/06/meeting-github-copilot-coding-agent/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Настройка Node-RED + Raspberry PI 3 + ZWave Razberry (Raspbian 9 Stretch)</title>
		<link>https://const.kiev.ua/2018/12/node-red-raspberry-pi-3-zwave-razberry/</link>
					<comments>https://const.kiev.ua/2018/12/node-red-raspberry-pi-3-zwave-razberry/#respond</comments>
		
		<dc:creator><![CDATA[const]]></dc:creator>
		<pubDate>Tue, 25 Dec 2018 16:43:05 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[home automation]]></category>
		<category><![CDATA[iot]]></category>
		<category><![CDATA[node-red]]></category>
		<category><![CDATA[raspberry]]></category>
		<category><![CDATA[z-wave]]></category>
		<guid isPermaLink="false">http://const.kiev.ua/?p=535</guid>

					<description><![CDATA[Для того, чтобы заработала связка Node-RED с Z-Wave (open-zwave) на RPI3, нужно выполнить следующий набор манипуляций: Сначала ставим из коробки Node-RED (настоятельно рекомендую делать все операции из-под юзера, например pi, без sudo) bash &#60;(curl -sL https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/update-nodejs-and-nodered sudo systemctl enable nodered.service Собираем руками open-zwave sudo apt install libudev-dev # ставим зависимости git clone https://github.com/OpenZWave/open-zwave make -j...]]></description>
										<content:encoded><![CDATA[<p>Для того, чтобы заработала связка Node-RED с Z-Wave (open-zwave) на RPI3, нужно выполнить следующий набор манипуляций:</p>
<p><span id="more-535"></span></p>
<ol>
<li>Сначала ставим из коробки Node-RED (настоятельно рекомендую делать все операции из-под юзера, например pi, без sudo)
<pre>bash &lt;(curl -sL https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/update-nodejs-and-nodered
sudo systemctl enable nodered.service</pre>
</li>
<li>Собираем руками open-zwave
<pre>sudo apt install libudev-dev # ставим зависимости
git clone https://github.com/OpenZWave/open-zwave
make -j 4
sudo make install # чтобы npm смог найти потом либу
# если это не сделать, то потом при запуске node-red в логе
# будут жалобы на линк: Error: libopenzwave.so.1.4: cannot open shared object file: No such file or directory
export LD_LIBRARY_PATH=/usr/local/lib
sudo ldconfig</pre>
</li>
<li>Для корректной работоспособности Razberry на RPI3 нужно отключить bluetooth, потому что они оба используют один и тот же UART
<pre>в /boot/config.txt добавить строчку
dtoverlay=pi3-disable-bt</pre>
</li>
<li>Устанавливаем в node-red нужные ноды
<pre>cd ~/.node-red
npm install openzwave-shared
npm install node-red-contrib-openzwave</pre>
</li>
<li>Для того, чтобы node-red смогла открыть порт /dev/ttyAMA0 (через который работает razberry) меняем настройку
<pre>systemctl mask serial-getty@ttyAMA0.service
в файле /boot/cmdline.txt убираем <code>console=serial0,115200</code> чтобы ядро перестало писать в serial</pre>
</li>
<li>reboot</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://const.kiev.ua/2018/12/node-red-raspberry-pi-3-zwave-razberry/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>VirtualKD + Windows 10</title>
		<link>https://const.kiev.ua/2017/11/virtualkd-windows-10/</link>
					<comments>https://const.kiev.ua/2017/11/virtualkd-windows-10/#respond</comments>
		
		<dc:creator><![CDATA[const]]></dc:creator>
		<pubDate>Thu, 30 Nov 2017 17:38:05 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Программирование]]></category>
		<guid isPermaLink="false">http://const.kiev.ua/?p=530</guid>

					<description><![CDATA[Если вдруг нужно, чтобы взлетел VirtualKD с гостевой Windows 10, то после инсталляции оного внутри машины, нужно ещё обязательно выполнить bcdedit /dbgsettings serial, иначе кина не будет. Сэкономит часик времени на рисчёрч &#8220;а чо оно не работает&#8221;.]]></description>
										<content:encoded><![CDATA[<p>Если вдруг нужно, чтобы взлетел VirtualKD с гостевой Windows 10, то после инсталляции оного внутри машины, нужно ещё обязательно выполнить bcdedit /dbgsettings serial, иначе кина не будет. Сэкономит часик времени на рисчёрч &#8220;а чо оно не работает&#8221;.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://const.kiev.ua/2017/11/virtualkd-windows-10/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Google Crashpad</title>
		<link>https://const.kiev.ua/2017/11/google-crashpad/</link>
					<comments>https://const.kiev.ua/2017/11/google-crashpad/#respond</comments>
		
		<dc:creator><![CDATA[const]]></dc:creator>
		<pubDate>Thu, 02 Nov 2017 13:20:04 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[crashpad]]></category>
		<category><![CDATA[gyp]]></category>
		<category><![CDATA[visual studio]]></category>
		<category><![CDATA[заметка погромиста]]></category>
		<category><![CDATA[Программирование]]></category>
		<guid isPermaLink="false">http://const.kiev.ua/?p=526</guid>

					<description><![CDATA[Для того, чтобы собрать crashpad под Windows с DLL runtime (/MD /MDd), нужно создать в своём домашнем каталоге (c:/users/konst например) подкаталог .gyp и в него положить файл include.gypi со следующим содержимым: {   'target_defaults': {     'configurations': {       'Release': {         'target_conditions': [           ['OS=="win"', {             'msvs_settings': {                'VCCLCompilerTool': {                   'RuntimeLibrary':...]]></description>
										<content:encoded><![CDATA[<p>Для того, чтобы собрать crashpad под Windows с DLL runtime (/MD /MDd), нужно создать в своём домашнем каталоге (c:/users/konst например) подкаталог .gyp и в него положить файл include.gypi со следующим содержимым:</p>
<pre>{
  'target_defaults': {
    'configurations': {
      'Release': {
        'target_conditions': [
          ['OS=="win"', {
            'msvs_settings': {
               'VCCLCompilerTool': {
                  'RuntimeLibrary': '2',
                }, 
             },
          }],
        ],
      },
      'Debug': {
        'target_conditions': [
          ['OS=="win"', {
            'msvs_settings': {
               'VCCLCompilerTool': {
                   'RuntimeLibrary': '3',
                }, 
            },
          }],
        ],
      },
    },
  },
}</pre>
<p>И пусть это сэкономит те полдня, которые пришлось потратить, чтобы выяснить этот факт.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://const.kiev.ua/2017/11/google-crashpad/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Motorola Droid Turbo XT1254 CDMA tuning</title>
		<link>https://const.kiev.ua/2017/01/motorola-droid-turbo-xt1254-cdma-tuning/</link>
					<comments>https://const.kiev.ua/2017/01/motorola-droid-turbo-xt1254-cdma-tuning/#respond</comments>
		
		<dc:creator><![CDATA[const]]></dc:creator>
		<pubDate>Sat, 14 Jan 2017 21:18:12 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">http://const.kiev.ua/?p=513</guid>

					<description><![CDATA[У моего телефона почему-то после каждой перепрошивки слетают настройки EVDO на Интертелекоме, из-за чего нужно править настройки. Т.к. я всё время забываю процедуру, то решил её сохранить тут. Запускаем телефон в режиме BP Tools (из fastboot bootloader меню) Идём в Device Manager, выбираем устройство diag_mdm и ручками ставим драйвер Motorola QC Diag Port Запускаем DFS...]]></description>
										<content:encoded><![CDATA[<p>У моего телефона почему-то после каждой перепрошивки слетают настройки EVDO на Интертелекоме, из-за чего нужно править настройки. Т.к. я всё время забываю процедуру, то решил её сохранить тут.</p>
<ol>
<li>Запускаем телефон в режиме BP Tools (из fastboot bootloader меню)</li>
<li>Идём в Device Manager, выбираем устройство diag_mdm и ручками ставим драйвер Motorola QC Diag Port</li>
<li>Запускаем DFS CDMA Tool (нужна старая версия, можно было скачать <a href="http://netmarket.kiev.ua/image/data/drivers/DFS%2014.06.01.0.zip">тут</a>)</li>
<li>Вводим SPC 000000 и переходим во вкладку Programming</li>
<li>Находим вкладку Data и снимаем галку &#8220;Authentification require password encryption&#8221;.</li>
<li>Ребутаемся, работает 3G (EVDO Rev.A)</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://const.kiev.ua/2017/01/motorola-droid-turbo-xt1254-cdma-tuning/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>ESP8266 и датчик движения с фольгой</title>
		<link>https://const.kiev.ua/2017/01/esp8266-and-motion-sensor/</link>
					<comments>https://const.kiev.ua/2017/01/esp8266-and-motion-sensor/#respond</comments>
		
		<dc:creator><![CDATA[const]]></dc:creator>
		<pubDate>Sat, 07 Jan 2017 14:35:13 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[biss0001]]></category>
		<category><![CDATA[esp8266]]></category>
		<category><![CDATA[home automation]]></category>
		<category><![CDATA[iot]]></category>
		<guid isPermaLink="false">http://const.kiev.ua/?p=486</guid>

					<description><![CDATA[Небольшой пост о том, как я сделал включение подсветки на датчике движения, но свет начал включаться произвольно и на помощь пришла обычная фольга.]]></description>
										<content:encoded><![CDATA[<p>Когда-то я сделал подсветку рабочей поверхности на кухне с помощью БП, выключателя и трёх метров диодной ленты. Подходишь, нажимаешь выключатель, появляется свет, делаешь своё дело, уходишь &#8211; выключаешь свет. Но прогресс не стоит на месте и захотелось выключатель сделать чуть более умным, чтобы он включался по входу на кухню и не нужно было щёлкать рукой, а также попутно измерял температуру и влажность на кухне, благо компоненты на алиэкспрессе стоят копейки.</p>
<p>В результате на базе ESP8266, датчика движения BISS0001, сенсора AM2302 (DHT-22) и релешки OMRON G3MB-202P (вообще можно обойтись мосфетом, но было интересно SSD реле потыкать) был сделан контроллер ленты, который попутно сливал информацию о погоде на кухне. Всё это было аккуратно собрано в одну 6см распределительную коробочку шнайдер из &#8220;новой линии&#8221;. Напишу отдельно о процессе создания такой штуки.</p>
<div class="aligncenter"><a href="https://const.kiev.ua/wp-content/uploads/2017/01/esp-scargill.jpg"><img fetchpriority="high" decoding="async" class="wp-image-488" src="https://const.kiev.ua/wp-content/uploads/2017/01/esp-scargill.jpg" width="240" height="246" /></a><a href="https://const.kiev.ua/wp-content/uploads/2017/01/biss.jpg"><img decoding="async" class="wp-image-494" src="https://const.kiev.ua/wp-content/uploads/2017/01/biss.jpg" width="240" height="218" /></a></div>
<p>Теоретически схема работала отлично, на практике тоже, датчик включал свет, через 40 секунд после последнего срабатывания выключался, температура с влажностью сливались, кроме одного нюанса: иногда свет включался сам. Системность выяснить не удавалось, поэтому пришлось демонтировать плату управления, прогреть её, почистить от флюса (я ещё тот паяльщик), но это не помогло. Пришлось гуглить и оказалось, что датчик движения чувствителен к Wi-Fi радио ESP, иными словами, когда контроллер передаёт информацию, то он может вызвать ложно-позитивное срабатывание сенсора, что приводит к включению света, несмотря на отсутствие кого-либо на кухне. Ну что же, красивую упаковку пришлось чуть разобрать и датчик вынести наружу, чтобы отдалить от радио-антенны и уменьшить наводки.</p>
<p><figure id="attachment_487" aria-describedby="caption-attachment-487" style="width: 240px" class="wp-caption alignleft"><a href="https://const.kiev.ua/wp-content/uploads/2017/01/biss-foil.jpg"><img decoding="async" class="wp-image-487" src="https://const.kiev.ua/wp-content/uploads/2017/01/biss-foil.jpg" width="240" height="237" /></a><figcaption id="caption-attachment-487" class="wp-caption-text">Экран из фольги</figcaption></figure></p>
<p>Свет стал включаться реже, но всё равно включается сам по себе. Пришлось заварить кофею и начать думать, как же поступить ещё&#8230; В голову пришла мысль заэкранировать датчик, под рукой оказалась продуктовая фольга &#8211; взял небольшой кусок, обмотал датчик движения, заизолировал изолентой внутри и снаружи и запустил систему заново.<br />
Свет перестал включаться произвольно совсем! Теперь когда кто-то подходит к столешнице &#8211; ему услужливо включается подсветка и работает, пока этот кто-то там находится и что-то делает, после того, как человек уходит &#8211; свет отключается, а обычная кухонная фольга отлично экранирует наводки от радиосигнала Wi-Fi.</p>
<p><figure id="attachment_502" aria-describedby="caption-attachment-502" style="width: 800px" class="wp-caption aligncenter"><a href="https://const.kiev.ua/wp-content/uploads/2017/01/light-system.jpg"><img loading="lazy" decoding="async" class="wp-image-502" src="https://const.kiev.ua/wp-content/uploads/2017/01/light-system.jpg" width="800" height="399" /></a><figcaption id="caption-attachment-502" class="wp-caption-text">Блок питания, контроллер и вынесенный датчик движения</figcaption></figure></p>
<p><figure id="attachment_490" aria-describedby="caption-attachment-490" style="width: 800px" class="wp-caption aligncenter"><a href="https://const.kiev.ua/wp-content/uploads/2017/01/kitchen-light.jpg"><img loading="lazy" decoding="async" class="wp-image-490" src="https://const.kiev.ua/wp-content/uploads/2017/01/kitchen-light.jpg" width="800" height="482" /></a><figcaption id="caption-attachment-490" class="wp-caption-text">Подсветка кухни в деле</figcaption></figure></p>
]]></content:encoded>
					
					<wfw:commentRss>https://const.kiev.ua/2017/01/esp8266-and-motion-sensor/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>uwsgi</title>
		<link>https://const.kiev.ua/2016/12/uwsgi/</link>
					<comments>https://const.kiev.ua/2016/12/uwsgi/#respond</comments>
		
		<dc:creator><![CDATA[const]]></dc:creator>
		<pubDate>Sun, 11 Dec 2016 19:32:16 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[uwsgi]]></category>
		<guid isPermaLink="false">http://const.kiev.ua/?p=480</guid>

					<description><![CDATA[Случайно обнаружилось, что в ini конфиге uwsgi важен порядок объявления параметров, поэтому если сначала объявить virtualenv, а потом указать подключение плагина python3, то будет попытка завестись с системным питоном.]]></description>
										<content:encoded><![CDATA[<p>Случайно обнаружилось, что в ini конфиге uwsgi важен порядок объявления параметров, поэтому если сначала объявить virtualenv, а потом указать подключение плагина python3, то будет попытка завестись с системным питоном.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://const.kiev.ua/2016/12/uwsgi/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>PostgreSQL backup to Azure</title>
		<link>https://const.kiev.ua/2016/11/postgresql-backup-to-azure/</link>
					<comments>https://const.kiev.ua/2016/11/postgresql-backup-to-azure/#respond</comments>
		
		<dc:creator><![CDATA[const]]></dc:creator>
		<pubDate>Wed, 30 Nov 2016 18:33:41 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[postgresql]]></category>
		<guid isPermaLink="false">http://const.kiev.ua/?p=466</guid>

					<description><![CDATA[С появлением облачных хранилищ стало грешным не использовать их возможности по хранению террабайтов данных за копейки, поэтому будем сохранять туда Continuous Archive данных из PostgreSQL. В нашем случае действие происходит на базе Ubuntu 14, PostgreSQL 9.5 установлен локально. Первым шагом нам необходимо установить сам pghoard и supervisor, т.к. systemd нет, а запускать демона с системой...]]></description>
										<content:encoded><![CDATA[<p>С появлением облачных хранилищ стало грешным не использовать их возможности по хранению террабайтов данных за копейки, поэтому будем сохранять туда Continuous Archive данных из PostgreSQL.</p>
<p>В нашем случае действие происходит на базе Ubuntu 14, PostgreSQL 9.5 установлен локально.<br />
Первым шагом нам необходимо установить сам pghoard и supervisor, т.к. systemd нет, а запускать демона с системой нужно.</p>
<p>Текущая версия pghoard 1.4 в pypi нам не подходит (в ней нету поддержки новых модулей azure-storage), поэтому инсталлировать её нужно из репозитория, а поскольку pghoard работает только с третьим питоном, то делаем это с помощью pip3<br />
UPDATE:<br />
предварительно нужно установить модули:</p>
<pre><code>azure
azure-storage==0.33
</code></pre>
<p>и проапгрейдить requests до версии 2.10+<br />
END UPDATE</p>
<pre><code>pip3 install git+https://github.com/ohmu/pghoard
apt-get install supervisor
</code></pre>
<p>Для автозапуска демона создаём конфигурационный файл pghoard.conf с минимально необходимым контентом и кладём его в <code>/etc/supervisor/conf.d/</code></p>
<pre><code>[program:pghoard]
user = postgres  # Запускать нужно от имени postgres, иначе не удастся подключиться к СУБД
group = postgres
directory = /var/lib/pghoard
command = /usr/local/bin/pghoard /var/lib/pghoard/pghoard.json
autostart=true
autorestart=true
environment=HOME="/var/lib/postgresql"  # Должен быть HOME пользователя postgres (туда записывается пароль и потом оттуда считывается)
</code></pre>
<p>Создаём пользователя в postgresql для выполнения репликации:<br />
<code>psql -c "CREATE USER pghoard PASSWORD 'hoardpassword' REPLICATION"</code></p>
<p>И вносим в <code>/etc/postgresql/9.5/main/pg_hba.conf</code> запись, разрешающую выполнять репликацию:<br />
<code>host    replication     pghoard         127.0.0.1/32            md5</code></p>
<p>В конфигурационный файл postgresql.conf нужно внести изменения, разрешающие выполнять репликацию:</p>
<pre><code>max_wal_senders = 2
wal_level = archive  # 'hot_standby' or 'logical' are also ok
</code></pre>
<p>Перезапускаем postgresql и настраиваем pghoard на работу с Azure:</p>
<pre><code>{
        "backup_location": "/var/lib/pghoard",
        "backup_sites": {
                "mysite": {
                        "nodes": [
                        {
                                "host": "127.0.0.1",
                                "password": "hoardpassword",
                                "port": 5432,
                                "user": "pghoard"
                        }
                        ],
                        "object_storage": {
                                "storage_type": "azure",
                                "account_name": "&lt;storage-account&gt;",
                                "account_key": "&lt;storage-account-key&gt;",
                                "bucket_name": "&lt;bucket-name&gt;"
                        }
                }
        }
}

</code></pre>
<p>После этого выполняем service supervisor restart и наблюдаем, как бекапы заливаются в azure blob storage.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://const.kiev.ua/2016/11/postgresql-backup-to-azure/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Home Automation Framework</title>
		<link>https://const.kiev.ua/2016/10/home-automation-framework/</link>
					<comments>https://const.kiev.ua/2016/10/home-automation-framework/#respond</comments>
		
		<dc:creator><![CDATA[const]]></dc:creator>
		<pubDate>Sun, 02 Oct 2016 20:56:43 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[domoticz]]></category>
		<category><![CDATA[esp8266]]></category>
		<category><![CDATA[home automation]]></category>
		<category><![CDATA[iot]]></category>
		<category><![CDATA[mqtt]]></category>
		<category><![CDATA[z-wave]]></category>
		<guid isPermaLink="false">http://const.kiev.ua/?p=447</guid>

					<description><![CDATA[Умный дом, или как программисту (и не только) добавить автоматики в своё жильё. Поделюсь своим опытом начального внедрения Z-Wave, а потом и самодельных девайсов в квартире.]]></description>
										<content:encoded><![CDATA[<p>Умный дом, или как программисту (и не только) добавить автоматики в своё жильё. Начну делиться своим опытом начального внедрения Z-Wave, а потом и самодельных девайсов в квартире.</p>
<p>В настоящее время для создания умного дома есть огромное количество различных решений. Если вы любитель DIY, или хотите сэкономить, а может и то, и другое &#8211; рекомендую обратить внимание на микросхемы ESP8266, или Arduino + nRF24. На базе ESP можно построить систему используя существующую домашнюю сеть Wi-Fi, на базе nRF можно построить систему по своей беспроводной сети, тоже работающией 2.4 ГГц, но не Wi-Fi, зато с преимуществом в виде возможности ретрансляции сигнала, т.е. каждая единица сети (нода) может общаться не только с контроллером, но и с другими нодами. Фактически mesh-сеть.</p>
<p><figure id="attachment_450" aria-describedby="caption-attachment-450" style="width: 320px" class="wp-caption alignnone"><a href="https://const.kiev.ua/wp-content/uploads/2016/10/esp_size.jpg"><img loading="lazy" decoding="async" class="wp-image-450" src="https://const.kiev.ua/wp-content/uploads/2016/10/esp_size.jpg" alt="ESP-12F" width="320" height="569" /></a><figcaption id="caption-attachment-450" class="wp-caption-text">Это &#8220;ядро&#8221; умного устройства на базе ESP-12F (8266)</figcaption></figure></p>
<p>С экономической точки зрения ESP-12F стоит на алиэкспрессе 1.80USD за штуку, ардуино стоит 1.60USD, но к ней ещё надо дополнительно покупать трансмиттер NRF24L01+, который стоит порядка 0.9USD.</p>
<p>При этом у ардуины 16-32КБ памяти и слабенький 16MHz Atmel процессор, в то время, как у ESP до 4 мегабайт флеша, аппаратный Wi-Fi с шифрованием и довольно мощный 32 битный RISC процессор, работающий на 80MHz. Выливается это всё в то, что по факту в ESP можно, не сильно напрягаясь, прикрутить OTA обновления и накрутить много всякой автономной логики, например целый веб-сервер, с помощью которого управлять нодой (т.е. обходиться вообще без контроллера). Тут можно посмотреть в сторону проекта NodeMCU, ребята запилили в прошивку интерпретатор LUA с помощью которого можно накручивать весьма сложную логику прямо на устройстве, не задействуя центральный сервер &#8211; т.е. создавать автономные системы.</p>
<p><figure id="attachment_451" aria-describedby="caption-attachment-451" style="width: 320px" class="wp-caption alignnone"><a href="https://const.kiev.ua/wp-content/uploads/2016/10/esp-nrf.jpg"><img loading="lazy" decoding="async" class="wp-image-451" src="https://const.kiev.ua/wp-content/uploads/2016/10/esp-nrf.jpg" alt="esp-nrf-arduino" width="320" height="415" /></a><figcaption id="caption-attachment-451" class="wp-caption-text">nRF24 + Arduino Pro Mini на фоне ESP-12</figcaption></figure></p>
<p>Z-Wave</p>
<p>В случае же, если есть много денег, или неохота заморачиваться с паяльником, прошивками и разного рода экспериментами &#8211; можно посмотреть на Z-Wave:<br />
это уже вполне mature, production решение. В наличии обилие устройств самого разного назначения &#8211; и выключатели, и реле, и термостаты с датчиками &#8211; бери и образумливай дом хоть сейчас. Стоимость, при этом, немаленькая. Самое простое реле будет стоить порядка 25-30 евро, а контроллер вообще под две сотни тянет.</p>
<p><a href="https://const.kiev.ua/wp-content/uploads/2016/10/zw_for_2consumer2.jpg"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-455" src="https://const.kiev.ua/wp-content/uploads/2016/10/zw_for_2consumer2.jpg" alt="z-wave promo" width="637" height="303" /></a></p>
<p>После нескольких лет использования Z-Wave оказалось, что я вообще сторонник гибридных решений. В части дома используется Z-Wave, в другой части появляются новые модули на базе ESP.</p>
<p>Чтобы всё это разнообразие взлетело, я использую в качестве контроллера Raspberry PI, к которой добавлена плата расширения RaZberry, позволяющая связываться с Z-Wave устройствами. Рядом с ней добавлена плата для связи с nRF24 устройствами, а связь с ESP осуществляется через локальную сеть.</p>
<p>До тех пор, пока я использовал только Z-Wave &#8211; в качестве контроллера мне хватало софта от RaZBerry, под названием Z-Way, но после того, как началась экспансия на DIY устройства &#8211; пришлось искать систему, которая сможет общаться со всем этим &#8220;зоопарком&#8221;. Мой выбор пал на Domoticz. Он умеет работать и с z-wave посредством OpenZWave, и с Arduino + nRF при помощи MySensors сборки для RPi, и с ESP через MQTT, который оказался настолько мощным и удобным протоколом, что появились даже мысли попробовать, когда-то адаптировать MySensors (или как-то написать свою прошивку) на работу через него.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://const.kiev.ua/2016/10/home-automation-framework/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
