Quantcast
Channel: Short notes on everything
Viewing all 66 articles
Browse latest View live

Make a Peltier wort chiller to get off the hook of water mains

$
0
0
Recently I've decided to venture into an exciting world of homebrewing. Brewing your own beer mostly involves 2 types of manipulations with liquids, namely heating and cooling. While heating can be comparatively easily done with butane burner or electric heater, cooling is a slightly more complicated matter. There are several ways one can go about cooling his/her wort:

  1. Ice bath. As primitive as dropping your vat of wort in a sink or tub filled with mixture of ice and water. Impractical for bigger volumes and brew pots that you can't even lift. May be a great way to exercise for a rare combination of DIY brewer and weightlifter. 
    Ice bath
  2. Immersion chiller. A coil of copper through which cold mains water flows. You submerge it in your brew tank and magic happens.
    Immersion chiller
  3. Counterflow chiller. This one is similar to the previous variety except it's built as a coil within coil. Now you don't have to sterilize your copper coil and submerge it in wort. Inner coil is for hot wort that is recirculated until it's cool enough, outer coil is fed with mains water supply.
    Counterflow chiller
  4. Plate chiller. Basically it's a compact version of counterflow chiller where heat exchange takes place in plates instead of coils.
    Plate chiller
The only place I have with enough free space for brewing is my garage, and it doesn't have any water except any that you may have brought along. This leaves only ice baths out of all this rich choice of cooling methods, but ice bath won't do because my brew pot is simply unwieldy.

Since I was always fascinated with new technology, soon enough a thought came to my mind  that Peltier elements are begging to be used in this scenario of cooling a limited volumes of liquid. That's how I decided to try making something like an immersion chiller with finite reserve of water cooled by Peltier modules.

This article is meant for those poor souls who, like myself,  don't even have access to a steady source of water on their brew day.

I started my experiments by buying
  • 2 40x40mm TEC modules
  • 1 aluminum heat exchanger
  • 1 12v diaphragm pump
  •  Flexible tubing ID 6m for pump
  •  Flexible tubing ID 8m for heat exchangers
  •  Thermal paste (considering that heatsinks and peltier modules don't have any mounting holes, you'd be better off with thermal glue) 
The only component left can be salvaged in the course of your usual dumpster dive - huge heatsinks , the variety used for cooling CPUs in computers. The bigger, the better.


From all this stuff we can fashion a sort of heat exchanging sandwich. It'll look like that:


Obviously cold side of TEC element goes to the heat exchanger, while the hot side goes to CPU heatsink with fan. 
Now, I wonder if this will even work... And if it does, how much current will this 1-sandwich setup suck? Let's try a basic arrangement where the pump gets water from the bucket, pumps it through our heat exchanger and back into the same bucket. Hose will be connected like this:


And there's the whole setup:
Hook it up to 12V (I recommend computer power supply. You can even make a bench PSU out of it, see my article) and if your wires haven't started smoking (1 TEC pulls about 5A, 2 of them - 10A) you will see water actually cooling down! The speed at which it'll cool is awful though. After 10 minutes of cooling the temperature of 1/10th of a bucket dropped only 2°C:

Start temp.
After 10 minutes.
Now, this calls for a small investigation. I'm going to do some benchmark tests to determine if cooling water via Peltier modules is viable and how much power and TEC modules is required to cool wort in volumes and time frames that brewing requires (around 30L from 100°C to 25°C in no more that 40-50 minutes).

Since 1-sandwich setup was nigh useless, I started benchmarking with 2-sandwich setup:

 I'll be posting results here as I get them:

# ModulesTotal currentTotal powerWater volumeStart temp °CFinal temp °CTemp diffTime

Настройка PID алгоритма нагрева жидкости

$
0
0

Продолжение статьи про пивоварню из стиральной машины

После того как все собрано и запрограммировано, самое время настроить PID алгоритм.

Здесь я напишу как это делается в общем и покажу как это делал я:

Как это делается

Надо подстроить коэффициенты Kp, Ki и Kd под конкретный объект (именно ваш нагреватель, котел, объем воды и т.д.). Самый простой способ настройки таков:

  1. Объекты с медленно меняющимся контролируемым параметром (температурой в моем случае) обычно работают с большим Kp, малым или нулевым Ki и нулевым Kd. В итоге должен получиться именно такой результат.
  2.  Начинаем с малого Kp, нулевого Ki и Kd. Насколько малый? В данный момент не скажешь точно, но можно взять минимальное значение при котором нагреватель будет всегда включен при разнице между заданной и текущей температурой в 10 градусов.
  3. Удваиваем Kp до тех пор, пока колебания не станут периодичными. Затем берем Kp в 2 раза меньше, чтобы колебания были либо стабильные, либо вообще отсутствовали.
  4. Устанавливаем небольшой Ki. Удваиваем его пока не начнутся колебания, затем берем его в 2 раза меньше, чтобы колебаний не было.
Если что-то не получается - бежим читать интернеты (я читал здесь) либо делаем все путем проб и ошибок (зная что будет большое значение Kp, малое Ki и нулевое Kd).

Как это делал я

  1. Заливаем код с режимом PLOT, подключаем Arduino к ПК и запускаем Serial plotter в Arduino IDE. Включаем нагрев и видим ползущий вверх график:

    А также медленно нагревающуюся воду...
  2. Рано или поздно текущая температура подойдет к заданной и возможно начнет колебаться вокруг нее. Если уже есть колебания то снижаем Kp.

    Setpoint = 40C
  3. Если же температура поддерживается, удваиваем Kp пока не график не станет колебаться. Затем ополовиваем Kp. У меня это получилось огромной цифрой - 16000

    Первая попытка угадать Kp - 2000. Температура держится стабильно

    Вторая попытка - 4к. То же.

    Дальше пошел итеративный процесс повышения Kp

    На Kp=16к мне стало скучно и я решил помешать воду рукой.
    Оттуда и проседание.

    На 16k уже видно небольние нестабильности.
    На Kp=32k показания начали колебаться.
  4. Теперь подстраиваем Ki. Начнем со 100 и посмотрим как он будет влиять на процесс.

    Если при чисто пропорциональном регулировании на одном Kp было четкое включение-отключение нагревателя вокруг установленной температуры, то теперь при проседании температуры ВОЗЛЕ установленной начинает потихоньку включаться обогрев. Например, при заданной темп. 50С и снижении показаний от 50.5С уже на 50.1С начинается небольшой обогрев. При чисто пропорциональном нагреве вода бы остывала до 50, и только потом начался бы нагрев.

    На графике не видно, но чем больше Ki тем раньше начинает компенсироваться потеря температуры.
    Теперь весь процесс настройки сведен к подстройке коэффициента Ki. Лично мне подошел 3000.
  5. Мои поздравления, теперь PID регулятор полностью настроен и готов к работе!

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

$
0
0
Сегодня я покажу, как перевести старую, жрущую батарейки газовую колонку на автономное питание (то есть будет работать вне зависимости от того, есть электричество или нет) которое не требует постоянной смены батареек.

Пациент

Итак, имеем: старую газовую колонку, которая питается от 2 батареек типа D:

При постоянном использовании батарейки приходилось менять примерно раз в 3 месяца. Не сказать бы что это большие деньги - примерно 50 руб. за батарейку, всего 100 руб., но продаются такие батареи не везде (обычно продают АА и ААА). В итоге лень победила и я решил избавиться от батареек.

Модификация колонки

Так как живу в съемной квартире, не хотелось никаким образом ломать колонку. Соответственно, все улучшения будут минимально инвазивными:
  • Покупаем в Китае 2 адаптера D на AA:


  • Делаем из одной фальшивую батарейку для подачи +, а из другой для подачи -. Для этого подпаиваемся к контактам изнутри адаптера вот так:

    Получится что-то подобное:


  • Адаптеры вставляем в отсек для батарей, потом к ним подсоединим выход нашего бесперебойника.


  • Проводим питание от колонки до бесперебойника. Я использовал витую пару, и Вам советую из-за того что будет меньше наводок по питанию. Провод тянется через все помещение от ванны к более сухому углу комнаты, так что это будет не лишним.
  • Соединяем адаптеры с витой парой. На это соединение часто будет плескаться вода, так что советую соединить провод так, как это делают на подводных лодках: соединение промазать 2компонентной эпоксидной смолой и , пока она высыхает, стянуть сверху термоусадкой.
На этом модификации закончены. Приступим к схеме нашего мини-ИБП.

Схема девайса и сборка

Схема довольно проста. В качестве основного источника питания я использую стабилизатор напряжения 1117 на 3.3В, в качестве резервного - 2 аккумулятора от мобильных телефонов которые параллельно заряжаются от 2 блоков питания на 5В, а после понижающий преобразователь делает из напряжения этих аккумуляторов 3.3В.
Приступим к сборке! Вот что нам понадобится (все можно достать либо в местном магазине электрики-электроники, либо в Китае):
  •  Для переменного тока (слева направо, сверху вниз) - выключатель, 2 кабельных ввода PG9,  2 разъема Wago серии 222, 4 ножевые клеммы, предохранитель и держатель для него.
  •  Для постоянного тока - стабилизатор LM1117-3.3, клеммник винтовой, 2 твердотельных предохранителя (PTC) на 0.5А, реле SPDT с катушкой 5В, макетная плата, 2 блока питания на 5В (можно выдернуть из зарядных устройств USB).
  •  Для резервного питания: электролитический конденсатор большого объема напряжением минимум 6.3В, 2 зарядных платы для литиевых аккумуляторов (у меня на основе TP4056), 2 аккумулятора от мобильных телефонов, понижающий конвертор на 3.3В и ток хотя бы 1А.
  • Коробка для всего этого.
  • Всякие мелочи типа электролитических и керамических конденсаторов, разъемов для крепления проводов к макетной плате.
Когда все собрано, можно начать:
Полный набор самоделкина.
  1. Прорезаем или просверливаем в коробке отверстия для кабельных вводов, кнопки и предохранителя. Мне очень помогло коническое сверло и очень острый нож типа hobby knife. Монтируем все это.


  2. Подключаем разъемы Wago 222 к выключателю питания. Потом к этим разъемам будем подводить 220В - очень удобно когда соединить провода можно просто руками.


  3. Начинаем подготавливать батареи. Их удобно организовывать как 2 модуля аккумулятор+зарядка+предохранитель PTC.


  4. Если Ваши батареи, как и мои, с подпружиненным контактом, то можно не уродовать батареи пайкой, а из кусочка медной шины изготовить контакты для них:


  5. Собираем часть схемы с переменным током.


  6. Подсоединяем оставшиеся провода к аккумуляторным модулям, приклеиваем зарядную плату к батарейке термоклеем:


  7. Соединяем блоки питания с аккумуляторными модулями. Готовим разъемы: от батареек к макетке и от блока питания к макетке.


  8. Собираем на макетной плате нашу схему переключения с одного источника на другой, а также понижение напряжения с 5 до 3.3В для основного питания.


  9. Осталось только все аккуратно подключить внутри коробки. Если Вы использовали разъемы, это будет легко:


  10. Вклеиваем все части системы в коробку термоклеем. Остается только закрыть коробку.


  11. Отключаем автоматы в квартире (Безопасность главное!11).


  12. 220В я взял из близлежащей розетки и аккуратно провел за дверной рамой.


  13. Монтируем мини-ИБП и включаем автоматы в квартире. При включении питания батареи должны начать заряжаться (красный свет) и дойти до полного заряда (синий свет). Поздравляю! Теперь Вы гордый обладатель газовой колонки которая работает при любых условиях и не требует смены батареек.

    Вид снизу:

AC power + battery backup for portable tankless gas water heater

$
0
0
This post I'm writing today will deal with tankless gas heaters. Not just any heaters, but the ones that are battery powered, such as this one:
Typical battery-powered tankless gas heater, bottom view.

As you can see on the right corner of this picture, a portable tankless gas heater uses two D-type batteries to ignite gas and keep the water valve open. Compared to more commonly sold mains-powered units, this one has an advantage of being able to heat water during power outage. There's one disadvantage, though: depending on how often you use it, you'll have to replace batteries sometimes as often as every 2 or 3 months! Being a lazy bum just as I am, one day I decided to overcome this disadvantage and make my heater work from mains, retaining the advantage of autonomy from power grid. How?

Today I will show you how to make your tankless gas water heater autonomous from mains electricity (that is, it will work even during power outages).

Pros: you won't have to constantly change batteries.
Cons: none! What are we waiting for, let's start!

Our patient

Given:
  • old tankless gas heater powered by two D-type batteries like those:

  • your adept hands.

Gas heater modifications

Since I live in a rented apartment, I did not want to modify the heater in any visible or irreversible way.Bearing that in mind, all improvements I made were minimally invasive. That's what you'll need to do:
  • Buy two D to AA adapters from China:


  • Craft two fake batteries from two pieces of wire and battery adapters. They will supply power to internal circuitry instead of conventional batteries.To make them, solder a wire to the backside of + and - contacts inside the adapter like this:


    That's what this trick is supposed to yield:


  • Plug the modified adapters into the battery compartment. The output of our uninterruptible power supply will be connected to them, eventually.


  • Stretch the wire from some dry corner where you'll plant your electronics to the gas heater. I used a twisted pair, and I advise you do the same to avoid crosstalk.
  • Connect the adapters with the twisted pair.This connection will be splashed on, that's why I connected the wires submarine-style: smeared some 2-part epoxy resin there the wires were twisted together and applied a heat shrink on top while it was drying out. That's the easiest way I found to get a waterproof connection.
This completes the modifications part. Let's proceed to the schematic of our mini-UPS.

Schematic and assembly

The schematic is quite simple (as every schematic I made, ever 😀). For the main power source I use 1117 3.3Vvoltage regulator, and 2 cellphone batteries wired in series for backup. There batteries are charged from two 5V PSUs, and buck converter converts their combined voltage to 3.3V.
Here's what you'll need to assemble a thing like that (you can get it all from your local electric/electronics store or from China, the choice is yours):
  •  For AC part of the schematic (left to right, top to bottom) - AC switch, two PG9 cable glands,  two Wago connectors (222 series, 2 holes), four quick disconnect crimp terminals, 0.5A fuse and fuse holder.
  • For DC part - LM1117-3.3 voltage regulator, PCB mount screw terminal, two PTC fuses rated 0.5A, SPDT relay with 5V coil, perfboard, two 5V power supply units (can be yanked out of USB chargers).
  • For backup part: electrolytic capacitor rated at least 6.3V with capacity >1000uF, two lithium charger boards (mine are based on TP4056), two cellphone batteries, buck DC-DC converter with 3.3V and at least 1A output.
  • A project box where you'll cram all stuff I mentioned above.
  • All sorts of electronic trifles like electrolytic and ceramic capacitors, wire-to-board connectors etc...
When you've got it all, you may begin assembly:
A complete Jack-of-all-trades set.
  1. Cut and/or drill apertures in the box for cable glands, switch and fuse holder. Mount it. To make those holes, I found conical drill bit and very sharp hobby knife very handy.


  2. Connect Wago 222 to power switch. Mains voltage is to be connected to them - the ability to simply join the wires with your bare hands will come in handy when you'll be installing this box to some remote dusty corner. No crimping, screwing, etc...


  3. Let's prepare the batteries.They can be conveniently arranged as two modules consisting of battery + charging circuit + PTC fuse:


  4. If your batteries, like mine, came with spring-loaded contacts, you can try to avoid making them ugly after soldering wires directly to terminals, and make a male connectors from a piece of a copper bus for them:


  5. Finish assembling AC part of our mini-UPS.


  6. Connect the remaining wires to the battery modules, then hot glue the charging circuit to each module:


  7. Solder power supplies to battery modules. Prepare the connectors to connect batteries and power supplies to perfboard.


  8. Assemble the switching and regulating parts of the circuit on the perfboard.

  9. The only thing left now is to arrange everything neatly inside the box. If you used connectors, it'll be easy:


  10. Hot-glue everything to the bottom of the box. Test that it works (mine didn't work after assembly, turns out I connected 5V and GND to a single spot. Pay attention to details when soldering!).


  11. Switch the circuit breakers off (Safety first!11).


  12. I grabbed mains voltage from a nearby wall socket and carefully hid the wire behind the door frame. You can think of something more clever/visually appealing.

  13. Hook up mini-UPS and switch circuit breakers on. When the power on, the batteries should start charging (red light) and eventually reach full charge (blue light).
    Congratulations! You are now a proud owner of a tankless gas water heater that works in any conditions and does not require changing the batteries.


    Side view:

SMS GPS-tracker with Neoway M590 and ublox NEO-6

$
0
0
This post is a follow up on my series about GSM/GPRS module Neoway M590.
First post of the series concerned some basic module usage scenarios with Arduino like sending/receiving SMS, detecting a phone call and even using GPRS network, the second post was a more practical example of automated garage heater that can be controlled with SMS messages:
  1. Basic tutorial
  2. Remote control for garage heater 
This time I'll demonstrate a more sophisticated example of using this module - making a GPS tracker that sends its position to owner via SMS. We'll have to explore both GSM and GPS modules' power-saving settings to ensure long battery life of our resulting device. This tutorial will also complement the first tutorial I wrote with more detailed Neoway M590 assembly and startup guidelines.

Here's some helpful links with datasheets:

Essential hardware

  • Evidently, you'll need both Neoway M590 GSM/GPRS module and ublox NEO-6 GPS module. The former is usually conveniently sold as a (dirt cheap) assemble-it-yourself kit on Aliexpress and Taobao, while the latter can be procured as a ready-made PCB complete with a huge rectangular ceramic antenna.

    Neoway M590 GSM/GPRS module
    ublox NEO-6 GPS module

  • For the GPS logger iself we'll use the ol' trusty ATMega 328P. Actually, I happened to buy it as a set of  IC itself, DIP socket, 7805 voltage regulator, electrolytic capacitors and 16MHz crystal with 22pF capacitors. Not all of that will come in handy, but hey, it was 99 cents!
    The infamous ATMega328p that we all know as a heart of Arduino Uno. 8MHz crystal resonator in the middle.

  • 8MHz crystal resonator. Sadly, my kit didn't include this, and I had to pluck it out of some unfortunate piece of hardware I had lying around.
    8.000 printed on top evidently makes for 8Mhz crystal.

  • Lithium battery that you can salvage from someone's old mobile or just buy and a lithium battery charger like this one:
    TP4056 (datasheet) based charger. Can be bought cheaply and in great numbers on Aliexpress and the likes.

  • Assorted capacitors. Specifically, besides your run-of-the-mill electrolytic and ceramic caps, you'll need some large capacitance caps that can be found in charge pump circuits on motherboards.

  • Optionally, to test each piece of hardware before assembling the device you'll need: an Arduino,  some male and female jumper wires (don't know why I included a breadboard in this picture, but it might prove useful to you).

  • A pair of ham-fisted hands😀 (in my case, anyway)
That should be enough. Let's get started then?

Not much for such an advanced(ish) device.

    Assembling and testing M590 module

     Assembly

    Upon ripping open a package with (preferably ESD-protected, but who knows where you'll buy your module?) a plastic bag, you'll see a jumble of electronic parts:


    Close up pictures of the PCB tell a tale of which M590's pins are broken out on a pin header (quite a restrictive number for so many pins, that is):

    Top side
    Bottom side

    Soldering those is pretty straightforward, although there's still more than one way one could mess this up. Pin header, resistors (small black rectangular ones with numerals on them) and ceramic capacitors (small yellow ones) are non-polar, meaning you can solder them any way 'round. My kit lacked one ceramic capacitor, you can solder any other salvaged SMD ceramic cap in its place.

    Tantalum capacitor and LED's have to be soldered in a particular orientation to work. You can tell their polarity (and thus, the way you have to solder them) from markings on their body.

    Tantalum caps have a dark stripe on positive side:


    Surface mounted LEDs have 2 distinctive feature that differentiate anode from cathode, namely, a drawing on the bottom and 2 green spots just barely visible from above:


     Putting all the rest together should be easy. GSM module has a circle on silkscreen, denoting pin 1. You can look up module's pinout in Neoway M590 Hardware design manual . SIM card slot's silkscreen also clearly indicates how it should be placed with a triangular notch.

    That's how the assembled module looks:
    Top side
    Bottom side
    There's only one thing missing now. M590 hardware design manual mentions that it can draw high peak current from its power source, hence you need a beefy capacitor to store energy and smooth out those surges of current consumption to reduce the continuous current output requirements of your power source. The kit I've bought came with a measly 220uF capacitor, and that is only good for the power source that can supply an approximate 0.8A of current!

    Let's reduce these current requirements and solder a beefy electrolytic cap right on top of the PCB to the power lines:


    ^ NOT DOING THIS CAN LEAD TO MODULE CONTINUOUSLY RESETTING and spitting out something like this in serial port:
    MODEM:STARTUP
    MODEM:STARTUP
    MODEM:STARTUP
    MODEM:STARTUP
    MODEM:STARTUP
    MODEM:STARTUP
    MODEM:STARTUP

    Now, on to checking if it even works, because cheap don't always mean good...

    Testing

    My breakout board's pinout is as follows:

    PinFunction
    1GND
    2GND
    3Vcc
    4Vcc
    5NC
    6NC
    7TX (M590 pin 8)
    8RX(M590 pin 7)
    9NC
    10NC
    11NC
    12RING (M590 pin 10)
    13NC
    14ON/OFF (M590 pin 19)

    Thanks to the capacitor we've soldered we can power the module directly from Arduino Uno's on-board 3.3V voltage regulator. Simply connect your module to Arduino like this:

    Arduino pinM590 pin
    GNDGND (1 or 2)
    3.3VVCC (3 or 4)
    D8TX (8)
    D9RX (7)


    In previous blog posts I used SoftwareSerial.h library to talk to Neoway M590. It worked to an extent, but I was constantly plagued by distorted characters in serial output. Turns out it was this library all along, being too slow to recognise fast transitions on serial pins...

    Now I'm using AltSoftSerial library and I suggest you do the same (or pick another better software serial library for Arduino). Just look at the difference, it's like in those washing powder TV commercials:
    SoftwareSerial's garbled output
    AltSoftSerial. Sleek.

    Now, let's upload the code that checks if Neoway M590 module responds to AT commands. For that, use Echo sketch that comes with AltSoftSerial library modified so that it sets 115200 baud rate for altSerial (see screenshot above).

    After powering up M590, if it's LED doesn't start blinking, you'll have to short the module's ON/OFF and GND pins for at least 0.5 seconds. Once it starts blinking, you should see MODEM:STARTUP in Serial monitor. Try to type AT and send it with trailing CRLF to test communication both ways. The module should send OK back. 

    If it doesn't,  try to use my auto-detection code from the next paragraph. Double-check your connections. If it still doesn't work, it's as good as garbage, try another one😊

    From my previous Neoway tutorial I learned that though the default baud rate of M590 module should be 115200, in reality the modules that vendors ship sometimes bear the signs of being used before and are set up for another baud rate. To simplify  the matter of finding the right baud rate, I wrote a sketch that automatically determines your module's speed.
    Upload it and enjoy not having to do the manual determining as seen on screenshot down below:

    Assembling and testing NEO-6 module

    Not a lot to assemble here. Just snap the module's antenna connector in place and solder jumper wires to its 4 pins (Vcc, GND, RX, TX). Alternatively, don't be a caveman like me and do it properly - solder a pin header to module and connect jump wires to it... I also soldered a small capacitor to Vcc and GND for stability.

    Ready to go

    Get yourself some GPS decoding library like this one -> NeoGPS. It is extremely configurable and can be set up to use AltSoftSerial, NeoSWSerial or even the nasty SoftwareSerial libraries for software serial connection to GPS module, along with hardware serial ports found on Leonardo, Mega and such.
    NeoGPS  installation manual on GinHub can be really helpful. Although it strongly advises against using SoftwareSerial, it will do for testing purposes.

    Now, connect serial pins as per GPSport.h included in NeoGPS library:


    Arduino pinNEO-6 pin
    GNDGND
    3.3VVCC
    D4TX
    D3RX

    Now let's fire up the Arduino and upload slightly modified NMEA.ino from NeoGPS library examples folder:


    GPS modules usually need some time (around a minute) to start up and get a fix from satellites. And once it does get a fix, it will start blinking an on-board LED every second.


     That's when you should see a torrent of data in your Serial port. Latitude and longitude are there, too, without a decimal separator on 2nd place from the right. You can try and plug them into Google Maps and make sure GPS module works:

    TBD PIC WITH GPS OUTPUT AND A MAP

    GPS Tracker schematic and assembly

     
    The schematic is nothing extraordinary. GPS module's serial is connected to ATMega's Hardware Serial due to GPS library's utmost need in fast and reliable serial port that is apparent from NeoGPS documentation. M590's module's hooked up to second-fastest serial port: AltSoftSerial on pins D8 and D9.

    As you may have noticed, there's a new pin that wasn't there before - DTR pin on Neoway M590. That pin is utilized to put GSM module to sleep mode. Current consumption in sleep mode is decreased tenfold, so that's something to be desired.

    Unfortunately, my breakout board didn't expose DTR pin on module's pin header. We'll have to make some corrections:

    TBD PIC







    SMS GPS-tracker with Neoway M590 and ublox NEO-6 part 2. Assembling and programming the device

    $
    0
    0
    See PART 1 here.

    This blog post is a part of series about really cheap GSM/GPRS module Neoway M590:
    1. Neoway M590 GPRS Tutorial: sending and receiving files from/to SD card
    2. Application of Neoway M590: remote control for garage heater
    3. SMS GPS-tracker with Neoway M590 and ublox NEO-6 part 1. Gathering parts and testing

    Here's some helpful links with datasheets:

      SMS GPS-Tracker schematic and assembly


      The schematic is nothing extraordinary. GPS module's serial is connected to ATMega's Hardware Serial due to GPS library's utmost need in fast and reliable serial port that is apparent from NeoGPS documentation. M590's module's hooked up to the second-fastest serial port: AltSoftSerial on pins D8 and D9.

      Correspondence of Arduino pins to physical ATMega pins was determined thanks to this helpful drawing:


      As you may have noticed, there's a new pin that wasn't there before - DTR pin on Neoway M590. That pin is utilized to put GSM module to sleep mode. Current consumption in sleep mode is decreased tenfold, so that's something to be desired.

      Unfortunately, my breakout board didn't expose DTR pin on module's pin header. We'll have to make some corrections:


      The next logical step would be to plug the soldering iron and to rummage about your workshop for a small piece of perfboard.

      Some pictures of GPS tracker mid-assembly:

      TBD



      How to use Platformio to develop for generic STM32F103C8 board (a.k.a. BluePill) with Arduino framework

      $
      0
      0
      A great wiki article about BluePill hardware that I heavily used making this post:
      stm32duino wiki

      I couldn't find a decent one-piece manual online on this topic, so here goes:

      You'll need

      • The Blue pill (can be procured on eBay, Aliexpress etc.).

        And at a reasonable price, as well!
      • STLink programmer clone (same place, almost the same price range).


      • A computer that can run Atom IDE , hopefully without too much lagging.

      Step-by-step manual

      Okay, now that you've got everything on the list, we can start uploading some sample code to the blue pill.

      First off, follow the MANUAL (steps I. Atom and, optionally, II. Clang for Intelligent Code Completion) to install Github's Atom IDE and Platformio, which is a plugin for Atom. Code completion will just assist you while you type your code and is not essential.

      Then do the Setting Up the Project paragraph. As soon as you've copy-pasted the example code, you should define LED_BUILTIN as PC13 - that's where the blue pill has its blinky thing connected.



      The complete mapping of physical pins to Arduino pins can be seen on this handy pic:



      All that's left now is to configure the project to use Arduino framework and STLink to upload the resulting code. For that, your platformio.ini should look like this:




      Your Blink project should be able to successfully build now:
      Build and upload buttons are located on the vertical pane on the left corner.

      Try to upload now! Connect STLink to BluePill's programming pin header as follows:
      STLink pinBluePill pin
      GND (3 or 4)GND
      3.3V (7 or 8)3.3
      SWDIO (2)DIO
      SWCLK(6)DCLK

      Upload should be successful now and LED should blink. In some cases, you'll see this instead:

      To fix that, short the BOOT0 pin to 3.3V with a jumper (consult with pinout diagram again) and reset the microcontroller. You'll be able to upload again after that.

      The mode in which STM32 starts is determined by pins BOOT0 and BOOT1 :
      BOOT1BOOT0Boot mode
      X 0User Flash memory
      0 1 System memory (bootloader)
      1 1Embedded SRAM

      You'll have to reset the board again in bootloader mode to be able to upload again. Therefore, my workflow with bluepill is like this:
      1. Set  Bluepill to bootloader mode with jumpers.
      2. Upload my code, check if it works
      3. If it doesn't, reset Bluepill, fix the code and go to step 2.
      4. If everything is fine, Set  Bluepill to run my code at startup with jumpers.

      Libraries, serial monitor, and all the goodies we love in Arduino IDE

      Blinking the LED isn't all we do with microcontrollers, and eventually you have to program more advanced peripherals that GPIO. That's where Arduino steps in with its huge ecosystem of libraries to every taste.

      What do we have in Platformio? Turns out, almost as much libraries as in Arduino.

      GUI interface in PlatformIO is available too!
      Now, as for serial, TODO

      SMS GPS-трекер из Neoway M590 and ublox NEO-6 часть 1. Собираем детали и тестим

      $
      0
      0
      Это продолжение моей серии постов о GSM / GPRS модуле Neoway M590.

      Первый пост этой серии касался основных сценариев использования модуля с Arduino, таких как отправка/получение SMS, определение телефонного звонка вместе с номером звонящего и даже использование GPRS. Второй пост - более практичный пример автоматизированного управления обогревом гаража с помощью SMS-сообщений.

      В этот раз я продемонстрирую более сложный пример использования этого модуля - создание GPS-трекера, который отправляет свое местоположение владельцу по SMS. Нам придется изучить настройки энергосбережения GSM и GPS модулей, чтобы обеспечить более длительную работу от батареи у готового устройства. Это руководство из двух частей еще и дополнит первый пост серии более подробными инструкциями по сборке и первым шагам с Neoway M590.
      1. Neoway M590 GPRS Tutorial: sending and receiving files from/to SD card
      2. Application of Neoway M590: remote control for garage heater
      3. SMS GPS-трекер из Neoway M590 and ublox NEO-6 часть 2. Сборка и программирование

      Ссылки на даташиты по используемому оборудованию:

        Требуемое железо

        • Очевидно, нам понадобятся как GSM/GPRS модуль Neoway M590 и GPS модуль ublox NEO-6. Первый, как правило, продается как удобный и дешевый комплект для сборки на Aliexpress и Taobao (например вот такой набор с похожей на мою платой с разъемом на 14 контактовили вот такой - в два раза дешевле, но с другой платкой. Тот который купил я уже успел подорожать до 5.5 USD: ссылка на него). GPS модуль можно купить в виде готовой распаянной печатной платы с огромной прямоугольной керамической антенной (ссылка).

          GSM/GPRS модуль Neoway M590
          GPS модуль ublox NEO-6

        • Для GPS трекера мы используем старую добрую ATMega 328P. На самом деле, я ухитрился купить за небольшую цену набор из самой Меги, DIP-разъема, стабилизатора напряжения 7805, электролитических конденсаторов и 16МГц резонатора с двумя конденсаторами на 22пФ. Не все детали пригодятся, но блин, дешево же! Сейчас не смог найти тот комплект который покупал я, но вот это тоже отлично пойдет (5 штук ATMega328P).

          Чип ATMega328p, который известен как сердце Arduino Uno и просто неплохая надежная старая железка. 8МГц резонатор в металлическом корпусе посередине.

        • 8МГц резонатор. К сожалению, мой комплект ATMega не включал такого, и мне пришлось вырвать его из какой-то несчастной железки.

          Надпись 8.000 сверху - явный знак 8МГц резонатора.

        • Литиевая батарея, которую можно достать из старого мобильного или просто купить + зарядное устройство для литиевых батарей, например вот такое:

          З/У на базе микросхемы TP4056 (даташит). Можно купить дешево и в большом количестве на Aliexpress и подобных магазинах.

        • Ассортимент конденсаторов. В частности, помимо стандартных электролитических и керамических кондеров, нам понадобятся большие конденсаторы большой емкости (>1000мкФ), которые можно найти на любой материнской плате.


        • Опционально - чтобы протестировать каждую часть оборудования перед сборкой устройства, вам понадобятся: Arduino, разные проводки для макетной платы (не знаю, я еще сфотографировал макетную плату, но вообще и она может пригодится для удобства).


        • Пара кривоватых рук😀 (по крайней мере у меня так)
        Кажется, все. Ну что, начнем?

        Не так уж и много деталей для такого девайса.

          Сборка и тест M590

          Сборка

          Когда Вы распакуете свой пакет из Китая (надеюсь, с защитой от статики, но кто знает...), Вы увидите кучку всяких-разных деталей:


          Фото печатной платы отлично демонстрируют, какие контакты M590 выведены на штырьковый разъем (довольно малое число, я бы сказал):

          Верх печатной платы
          Низ печатной платы

          Процесс пайки комплекта довольно прост, хотя даже это простое дело можно зафакапить.Разъемы, резисторы (маленькие черные прямоугольники с цифрами) и керамические конденсаторы (маленькие желтые прямоугольники) - неполярные компоненты, что означает, что их можно припаять как угодно.В моем комплекте не было одного керамического конденсатора, если у Вас так же, то можете припаять на его место любой другой похожий конденсатор.

          Танталовый конденсатор и светодиоды должны быть припаяны в определенной ориентации для того чтобы они работали. Полярность таких деталей (то есть то, какой стороной их припаять) можно понять по маркировке на корпусе.

          На танталовых конденсаторах есть темная полоса со стороны + :


          SMT светодиоды имеют 2 отличительные особенности, которые отзличают анод от катода, а именно рисунок внизу и два зеленых пятна, которые едва видны сверху:


          Все остальное собирается проще простого. На посадочном месте модуля GSM есть белая точка, обозначающая первую ногу. Распиновку модуля смотрим в документе Neoway M590 Hardware design manual. По шелкографии на посадочном месте держателя SIM-карт также понятно, как его припаять благодаря треугольному скосу.

          Так вот выглядит собранный модуль:

          Верх печатной платы
          Низ печатной платы

          Теперь осталась только одна важная доработка.В мануале на M590 упоминается, что он может брать большие пиковые токи из своего источника питания, поэтому на линии питания надо добавить мощный конденсатор для хранения энергии и сглаживания этих импульсов, чтобы уменьшить требования к источнику питания.В моем комплекте M590 был небольшой конденсатор на 220 мкФ. Такой пойдет для питания модема от источника питания, который может предоставить не менее 0.8А постоянного тока!


          Давайте-ка уменьшим эту цифру и припаяем мощный электролит прямо поверх печатной платы к линиям питания:

          У меня 4700мкФ

          ^ ЕСЛИ ЭТО НЕ СДЕЛАТЬ ТО ЕСТЬ ШАНС ЧТО МОДУЛЬ БУДЕТ ПОСТОЯННО СБРАСЫВАТЬСЯи постоянно выдавать в последовательный порт что-то такое:
          MODEM:STARTUP
          MODEM:STARTUP
          MODEM:STARTUP
          MODEM:STARTUP
          MODEM:STARTUP
          MODEM:STARTUP
          MODEM:STARTUP

          Теперь проверим, работает ли вообще, потому что дешево - не всегда хорошо...

          Тест

          Распиновка моего модуля (ряд штыревых разъемов 2x7):

          НогаФункция
          1GND
          2GND
          3Vcc
          4Vcc
          5NC
          6NC
          7TX (M590 нога 8)
          8RX(M590 нога 7)
          9NC
          10NC
          11NC
          12RING (M590 нога 10)
          13NC
          14ON/OFF (M590 нога 19)

          Благодаря конденсатору, который мы припаяли, мы можем подключить модуль непосредственно к встроенному регулятору напряжения 3,3 В на Arduino Uno. Просто подключите свой модуль к Arduino следующим образом:

          Пин ArduinoПин M590
          GNDGND (1 or 2)
          3.3VVCC (3 or 4)
          D8TX (8)
          D9RX (7)


          В предыдущих постах я использовал библиотеку SoftwareSerial.hдля общения с Neoway M590. Это работало в какой-то степени, но меня постоянно преследовали глюки связанные с искажением символов. Оказывается, эта библиотека слишком медленная и из-за задержек при софтовом распознавании входного потока символов они иногда искажаются.

          Теперь я использую библиотеку AltSoftSerial, и предлагаю Вам сделать то же самое (или выбрать другую библиотеку для Arduino, но не SoftwareSerial.h). Просто посмотрите на разницу, это просто какая-то реклама стирального порошка:

          SoftwareSerial
          AltSoftSerial

          Теперь загрузим код, который проверяет, отвечает ли модуль Neoway M590 на AT команды. Для этого используйте немного модифицированный скетч Echo, который поставляется в примерах для AltSoftSerial. Надо поменять скорость altSerial на 115200 бод (см. скриншот выше).

          Если светодиод не начнет мигать после подсоединения питания к M590, значит нужно соединить контакты ON/OFFи GNDмодуля минимум на 0,5 секунды. После того светодиод на модуле начнет мигать, и в мониторе последовательного порта Arduino IDE должно появиться гордое MODEM: STARTUP. Попробуйте ввести строку ATи отправить ее с завершающей последовательностью CRLF в последовательном порте Arduino IDE для проверки связи в обоих направлениях. Модуль должен ответить OK. Если текста не видно, стоит попробовать мой скетч автоматического обнаружения из следующего абзаца. Еще раз проверьте свои соединения. Если он все еще не работает, то можно выкидывать. За такую цену можно купить штук пять таких модулей и попробовать каждый из них.😊

          В процессе написания моего предыдущего поста про Neoway M590 я узнал, что хоть скорость порта модуля по умолчанию должна быть 115200, на самом деле на модулях, поставляемых из Китая зачастую видны явные признаки Б/У (уже паяные ноги например) и соотвественно они часто бывают настроены на другую скорость. Чтобы упростить поиск правильной скорости , я написал скетч, который автоматически определяет скорость порта.
          Загрузите его и больше не нужно будет вручною пробовать каждую скорость:

          Сборка и тест модуля NEO-6

          Тут собирать почти нечего. Надо просто вдавить антенну в RF разъем модуля и припаяться к 4 контактам модуля (Vcc, GND, RX, TX). Неплохо бы не быть таким дикарем как я (фото внизу), и припаять штыревой разъем к модулю... Также для тестов я припаял небольшой конденсатор к Vcc и GND для стабильного питания.

          Готово


          Теперь нужна библиотека для декодирования GPS, например эта -> NeoGPS. Она очень конфигурируемая и может быть настроена на использование библиотек AltSoftSerial, NeoSWSerialили даже SoftwareSerial, и даже аппаратных последовательных портов на Leonardo, Mega и т. д. для подключения к модулю GPS.

          Я нашел руководство по установке NeoGPSна GinHub довольно полезным для разворачивания библиотеки. Хотя оно настоятельно не рекомендует использовать SoftwareSerial, для тестирования и она сойдет.


          Теперь подключим RX и TX модуля в соответствии с файлом GPSport.hиз NeoGPS:


          Пин Arduinо Пин NEO-6
          GNDGND
          3.3VVCC
          D4TX
          D3RX

          Теперь запустим Arduino и загрузим слегка модифицированный скетчи NMEA.inoиз примеров к библиотеке NeoGPS:


          Модулям GPS обычно требуется некоторое время (от 5 до 15 минут в отдаленных районах) для запуска и получения локации со спутников. Как только модуль получит фикс (координаты), он начнет мигать светодиодом два раза в секунду.


          Теперь в Мониторе посл. порта Arduino должен появиться поток данных GPS, включая широту и долготу в формате без десятичной точки. Можно попробовать вставить эти координаты в Google Maps и убедиться, что модуль GPS работает:

          Вроде бы правильно!

          Вот ссылка на ЧАСТЬ 2, где мы продолжим собирать GPS трекер и программировать его.

          SMS GPS-трекер из Neoway M590 and ublox NEO-6 часть 2. Сборка и программирование

          $
          0
          0
          Часть 1 ЗДЕСЬ.

          Это продолжение моей серии постов о GSM / GPRS модуле Neoway M590:
          1. Neoway M590 GPRS Tutorial: sending and receiving files from/to SD card
          2. Application of Neoway M590: remote control for garage heater
          3. SMS GPS-трекер из Neoway M590 and ublox NEO-6 часть 1. Собираем детали и тестим

          Ссылки на даташиты по используемому оборудованию:

          Принципиальная схема и сборка


          Схема трекера (ССЫЛКА НА PDF) довольно проста. Последовательный порт модуля GPS подключается к аппаратному UARTмеги из-за нужды библиотеки NeoGPSв быстром и надежном последовательном порту, что очевидно из документации к ней. Модуль M590 подключен к второму по скорости последовательному порту: AltSoftSerialна пинах D8 и D9.

          Соотвествие пинов Arduino физическим ножкам микросхемы было определено из этого полезного рисунка:



          Как вы, возможно, заметили, на схеме появилась новая ножка на модуле Neoway M590 - DTR. Эта нога используется для перевода GSM-модуля в спящий режим. Потребление тока в режиме сна сокращается в десять раз, так что это нам точно нужно.

          К сожалению, моя платка с модемом не выводит DTR на штыревой разъем. Придется внести некоторые изменения:


          Следующим логичным шагом будет включить паяльник и порыться по мастерской в поисках кусочка макетной платы.

          Мой девайс выполнен в форм-факторе "сэндвич".Такой стиль, как мне показалось,  приведет к самой компактной сборке.Платы расположены как 3 слоя: верхний (нижний на самом деле, первое фото перевернуто) занят модулем Neoway M590 с его огромным фильтрующим конденсатором, середина - ATMega и всей самодельной схемой, и нижний (верхний, то есть) с GPS-модулем и обеими антеннами (поэтому этот слой я и считаю верхним, антенны располагаются в верхней части устройства).

          Вот пара фото трекера в процессе сборки:

          Вот и "сендвич".
          Рим не один день строился, начинаем с малого
          Дорожки сделаны из сердцевины цельного провода - ни одна не порвется и не отвалится, как могут провода.
          Зарядка добавлена как дополнительный слой между верхним и средним.
          Готово! На этом фото явно видно, как З/У припаяно к плате. И то как я кривовато слепил все двусторонним скотчем.
          Выключатель питания укромно спрятан между слоями, чтобы избежать случайного переключения.
          Обе антенны сверху.
          Послойный вид готового устройства сбоку
          То же, спереди

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

          Готовое устройство

          Программирование

          Выбор ATMega328 не был случайным, я специально выбрал ее для упрощения процесса программирования при помощи Arduino.

          Берем программатор и подключаем к 6-контактному разъему для программирования.
          Вот такой программатор я использую (ссылки на переходники программатор):

          Программатор USBASP + переходник с 10 на 6 контактов.

          Запустим Arduino IDE попробуем загрузить любой пример кода чтобы проверить соединения и чип: выбираем целевую платформу и программатор и щелкаем "Загрузить при помощи программатора" (в большинстве ОС это Ctrl+Shift+U).

          Выбираем напряжение и тактовую частоту
          Выбираем прогамматор

          Так просто это лично у меня не получилось (ничего никогда не работает из коробки, блин!).

          Вот так мы будет дебажить нашу загрузку кода. Лично у меня всегда стоит эта галочка.

          Отмечаем в настройках Arduino IDE режим детального вывода информации при загрузки, и видим следующее:



          После пары часов ковыряния Гугла я нашел основную причину ошибки. Очевидно, чипы ATMega328P на заводе прошиваются на использование внутреннего генератора 1 МГц. Это слишком медленно, чтобы запрограммировать их с помощью USBASP с настройками, с которыми IDE вызывает его.

          Первая мысль, которая пришла ко мне после выяснения этого была: «Ну отлично, почему оно не работает я знаю, но как теперь проверить, что чип не дохлый?»

          Для этого нам понадобится avrdude. Выполним эту строку, чтобы проверить соединение с чипом без каких-либо изменений в прошивке (найдено на stackexchange):



          Если это работает, то наша ATMega работает и программируется. Теперь вот что надо сделать чтобы обойти медленный внутренний тактовый генератор: во-первых, создадим новую «медленную» версию программатора USBASP для Arduino IDE. Современные версии IDE запихивают конфигурационные файлы далеко в  папку пользователя (Для Windows будет что-то вроде  C:\Users\Пользователь\AppData\Local\Arduino15\packages\arduino\hardware\avr\Версия)

          Пришлось покопаться на жестком диске чтобы их найти...
          Вот ссылкана полезный мануал по настройке Arduino IDE. Согласно этому документу, вставим эти строки в programmers.txtпосле секции с USBASP:



          Перезапускаем Arduino IDE, выбираем программатор 'Slow USBASP'и пробуем загрузить снова... Работает! Скетч Blink.hex грузится, хотя частота мигания кажется... низковатой. В 8 раз медленне чем надо, если быть точным. Почему? Смотрим в лог загрузки... Ага! Фьюзысовершенно неправильные!



          > avrdude: safemode: Fuses OK (E:FF, H:D9, L:62).
          По-моему совсем не OK. Почему-то несмотря на то, что настройки фьюзов указаны для каждой платы в файле board.txt, IDE не прожигает правильные фьюзы даже если они неверные. Фьюзы прожигаются только при записи загрузчика, а мне он не нужен.

          AVRDude просто нуждается в небольшом толчке в правильном направлении, чтобы прожечь правильные фьюз биты. Просто оставим Arduino IDE открытым (чтобы Blink.hex не удалился), скопируем команду, которая загружает Blink.hex и запустим ее в консоли с небольшим дополнением в конце:



          Это должно решить проблему с аномальной скоростью чипа! Теперь можно переключиться на обычную конфигурацию USBASP в среде Arduino, поскольку теперь AVR работает на частоте 8 МГц.

          Скетч Arduino

          Вот финальный код для отправления GPS-координаты (а также опционально даты и времени GPS и баланса SIM-карты) в ответ на звонок (без энергосберегающих режимов).Вам нужно будет установить библиотеки AltSoftSerialи NeoGPS, чтобы все заработало:



          Пришлось обойти один сильный недостаток библиотеки AltSoftSerial, а именно тот факт что все функции которые зависят от Timer0 перестают работать - delay() and millis(). Чтобы заново получить функцию задержки выполнения кода на определенное время, я использую функцию setTimeout()у объекта Serial, оттуда и взялась функция newDelay().

          Тот же самый скетч с энергосбережением скоро появится чуть ниже... Пока что можно использовать верхний скетч, чтобы получать координаты трекера в виде ссылки на Google Maps в ответ на Ваш звонок. Просто этот скетч будет быстро разряжать батарею.

          ОБНОВЛЕНИЕ 4 июля 2017

          Код ниже отправляет вам те же данные, что и предыдущий, только теперь он использует режимы энергосбережения для AVR и Neoway M590. Дополнительно понадобится установить библиотеку LowPower. ATMega и GSM-модем проводят большую часть времени в режиме энергосбережения, пока кто-то не позвонит или не отправит СМС.



          Теперь, чтобы еще больше экономить заряд аккумулятора, можно отсоединить светодиодный индикатор питания на плате Neoway M590. Теперь мы экономим дополнительные 20 мА, что очень даже приятно!

          UART bridge from HM-10 to PC with Java application

          $
          0
          0
          Today we're going to explore the exciting world of (relatively) new wireless technologies with Bluetooth Low Energy modules.

          BLE was developed with power conservation in mind, a standard made to fit the market of battery-powered devices that can go on for months and even years without being recharged. What I had in mind for a module I purchased online was replacing Bluetooth 2 UART wireless modules with something modern.
          HM-10
          The module we're going to use is called HM-10. It was conceived by Jinan Huamao Technology company and as usual it can be found online here -> original, and as with all novel promising pieces of hardware there are appreciably cheaper clones on the market, too. They're supposed to perform the same as original, though I haven't had a chance to test one of those.

          HM-11
          Their line of products also includes HM-11 which is basically the same module with smaller footprint and fewer pins broken out. You can use HM-11 instead of HM-10 freely within this tutorial (here are links to original module and cheaper fake).

          Hardware setup

          HM-10 pinout diagram

          HM-10 can accept 2 - 3.7V as power input, so in order to quickly whip up a testing rig without all that voltage level converting stuff we'll need a 3.3V Arduino to act as a host MCU to BLE module.

          Pro Micro - 3.3V/8MHz is the most widespread 3.3V Arduino. Again, you can find it cheaper online here.
          Pro Micro - 3.3V/8MHz

          In case you don't want to wait for a proper dev board to arrive by post and you have an Arduino Uno handy, you can retrofit it to be 3.3V-powered (see my blog post about various Arduino improvements).

          3.3V-converted Uno with HM-10
          Connections are as follows:

          Arduino pinHM-10 pin
          D2TX
          D3RX
          VccVcc
          GNDGND

          Now let's just hook it all up according to table above and upload test sketch that passes everything as it is between SoftwareSerial port on pins 2 and 3 (that's where we have HM-10 connected) and Hardware Serial which we can see in Serial monitor window.
          Send AT through Serial monitor a couple of times (line termination should be set to 'No line ending'). If you see OK sent back to you, then the connections works.

          You'll also need a BLE dongle to connect your PC to HM-10. I found these work well.

          Tiny BLE dongle that I have.

          Software setup

          Prep up your environment

          You'll need any Linux distribution to make use of Intel's Bluetooth LE library (GitHub link). I'll be using Arch Linux, therefore all the console commands below will work on any Arch Linux distribution and on any other Linux distro with minor modifications (e.g. different package manager, different package names).
          So here's what you'll need:
          • Yaourt or any AUR-enabled package manager
          • IntelliJ IDEA Community Edition or any Java IDE of your choice (Eclipse, Netbeans, vim+javac etc...)
          • Git, CMake, Doxygen
          • Bluez - Bluetooth library for Linux
          • Arduino IDE

          In CMake-GUI window, click Configure button. In freshly-appeared settings tick BUILD_JAVA and change CMAKE_INSTALL_PREFIX to /usr (if you don't you'll get java.lang.UnsatisfiedLinkError: no tinyb in java.library.path error later). Click Generate and we're done here.

          CMAKE config.

          Now you have TinyB library installed in your system. There's a note in README file telling that in order for it to operate correctly, you should add -E flag to bluetooth service, but it seems that Bluez v.5.46 that I'm using has already moved BLE support from experimental to basic functions. Therefore, you probably won't need to do any further modifications too.

          ArchWiki has a splendid article on setting up Bluetooth in your system. It's basically just starting bluetooth.service (and enabling it if you can't be bothered to start it after each reboot). Check if it works by following Bluetoothctl section of an article and performing a trial run of scanning.

          Let's get to programming then!
          BLE is structured unlike Bluetooth 2 and 3. You can read detailed software-related aspects of BLE on Wiki.

          In short, BLE devices expose services with unique IDs, and each service may have several characteristics. You can think of characteristics as variables that can have READ, WRITE or READ and WRITE access.

          Each BLE device, HM-10 included, has a set of predefined services and characteristics that contain info about the device (e.g. device name). Beside those, it has exactly one custom service with one characteristic that we'll use to send and receive serial data. Detailed description of all characteristics and services follows below:





          To transmit data from HM-10 to host device: write it to HM-10 serial port. It then sends a notification to host device to say there is new data available.

          To receive data sent by HM-10: Subscribe to value change notification on custom characteristic. It works like a callback - when there is new data available, the function you supplied when you subscribed is called to handle incoming data.

          To transmit data from host device to HM-10: write it to custom characteristic. It will instantly be sent from HM-10 serial port to whatever device it's connected to.

          To receive data sent by host device: just stay tuned on module's RX/TX lines :)

          Custom characteristic length: 20 ASCII characters, so to send a string longer than 20 characters you'll have to split it to 20-char segments and send them in sequence.

          Java coding

          I'll be basing my code on examples that came with tinyb library. You can find them in tinyb/examples/java. Not much of them, but it's enough to get started fast. HelloTinyB.java example is supposed to receive temperature from some sort of BLE temp. sensor, let's change it and complement a bit to be able to send and receive data from HM-10.

          So here's the code -> IntelliJ IDEA project. Just connect Arduino with HM-10 and BLE dongle to USB port,  launch the Main class and behold 'hello' string being sent each second from your Java code to HM-10 (and Arduino) over the air!

          It works!

          Note that for some reason this library can not discover Generic access service, but I didn't need it anyway. :-)
          You can also type something back in Serial Monitor and see it received through UARTReceiveNotification's callback.

          Now that the feasibility of sending text back and forth over BLE has been proven, all that's left is to refactor this crappy sample code that I quickly fudged together.

          Here's the final refactored project that gives programmer transparent serial connection with HM-10 BLE module. It could be tailored to connect to a similar module by changing device's address, UART service and characteristic address and its length.

          Feel free to use it for anything you want (try not avoid killing someone though) and leave suggestions in comments below. Bye!

          The most detailed guide on programming and debugging BluePill under Linux with IDE

          $
          0
          0

          Riding on the coattails of recent Bluepill craze, I already wrote up an article about programming this board with Platformio IDE (Arduino framework included!).

          In case you didn't know, Bluepill is a generic name for tiny boards with ARM processor (STM32F103C8T6 -> specs on STMicroelectronics website) that are Arduino-compatible and often marketed as yet another Arduino-killer (sigh...).

          Here's your run-of-the-mill bluepill.

          This hype train just doesn't seem to stop just yet, so I decided to produce one more useful Bluepill tutorial.

          If you're looking for a cheap alternative to Arduino boards (with a price tag of just about $2), take a look at blog post above. The rest of you who just think this is a neat new board that can be used to learn real microcontroller programming - read on!
          When it comes to real work, Arduino IDE often simply lacks horsepower. It's simple and favored by many because of the great power of high-level hardware abstraction that Arduino API offers, but the same abstraction means that you're just limited by API's capabilities and its programming model.

          (in prof. Farnsworth voice) Good news, everyone! You can program Bluepill just as easily in C, with access to interrupts, registers etc. This is mainly done with mighty IDEs such as Keil. It offers tight integration with all STM32 microchips. Debugging, programming, you name it - all this can be configured in a couple of clicks here.

          Unfortunately, you'll have to pay big bucks to use it, and it only works in Windows. As a Linux user, I couldn't help wondering - can I have something as good in Linux? Turns out you can, and it's not much harder than installing an IDE. Here goes:

          Prerequisites

          You'll need the same bluepill + stlink adapter combo from my previous article. And a Linux machine, obviously, preferably 64 bit (only older versions of IDE are available for x86 architecture). My example is based upon Arch Linux.
          Software-wise, you're going to need cross-crompiler and some minor stuff too:
          Restart your PC so that udev rules for STLink programmer take effect.

          Installing OpenSTM32 Workbench

          1. You'll have to register on OpenSTM32 website to download it (or you could avoid registering), but you can use it completely for free afterwards. 
          2. Download the latest version of IDE here
          3. Launch the installer. It pretty much looks like an ordinary Windows installer:

            You may uncheck STLink Server.
            The least favorite part is waiting...

          Debugging and programming with Blink example

          Start eclipse executable (located in ~/Ac6/SystemWorkbench/ by default) and you'll be greeted by an old familiar Eclipse. What's next? Well, set up a project that can compile firmware for our target STM32F103 microcontroller, upload and debug it. That's where you'll see the difference between plain Eclipse and this one.
          1. Create a new C project
          2. Pick Executable  -> Empty project in Project type tree, and Ac6 STM32 MCU GCC toolchain. Enter your project's name.
          3. Leave Debug and Release configurations checked.
          4. In the next window, switch to Mcu tab, then pick your target. For Bluepill, it's going to be STM32F103C8Tx from STM32F1 series.
          5. After clicking Next you may pick any additional development libraries provided by STMicro. You can pick No firmware option (aka CMSIS) - then you'll have to manually manipulate your MCU's registers to make it work. In case you want something more high-level, there's the choice between StdPeriph library (older, less bugs, quite low-level) and CubeHAL (newer, used to be a lot of bugs but that's probably not true anymore. High-level). If in doubt, there's lots of reading material about these libraries online.
          6. That's it! Click finish and your project can be built. No feat, that, considering it's empty for now. Let's add some blinky code to /src/main.c:
            If everything's ok, your project is supposed to build without errors.
          Our code builds now, but how to upload it to target? That's no linear process for bluepill, but once you do it, you'll be able to upload and debug your code in one click! At this point, you have to connect Bluepill to your computer with STLink programmer. The connection diagram is the same as in my previous post.

          Here's how you set up OpenSTM32:
          1. In your workspace, create a file named bluepill_debug.cfg with following contents:
          2. Open Debug configurations window:
            Create a new Ac6 STM32 Debugging configuration:
          3. Switch to Debugger tab. That's where magic starts. First unintuitive thing about OpenSTM32 Workbench is the fact that GDB and OpenOCD executables that come bundled with it don't mix well with your system's libraries. If you don't replace bundled executables, you're going to see "Could not determine GDB version using command" error:
            That's why we need to replace ${openstm32_compiler_path}/arm-none-eabi-gdb and "${openstm32_openocd_path}/openocd" with /usr/bin/arm-none-eabi-gdb and /usr/bin/openocd respectively. The automatically-generated configuration script is no good either - it doesn't take into account the lack of RST line. That's why you should pick your script from Step 1.
          4. Click Apply and then Debug. Here's what happens next: if your bluepill is connected to PC through STLink programmer, IDE will switch to Debugging perspective, upload your code and stop it at the first line. You're free to define breakpoints, step through lines one at a time, or just press F8 and behold the LED blink fast.
          The same configuration can be used from Run button - acting as the equivalent of Upload button. If everything worked, you're all set to develop full-blown programs for your favorite inexpensive ARM board.

          Troubleshooting

          Now, let's move on to special cases.

          In older versions of IDE this configuration skipped "Launch OpenOCD" part, which resulted in errors like "Remote debugging using localhost:3333 Remote connection closed" when trying to run GDB. I found that manually running OpenOCD as an external tool prior to debugging or uploading does the trick. And here's how:
          • Go to External Tools configuration.
          • Enter the following details:
            Location -> /usr/bin/openocd
            Working directory -> /usr/bin
            Arguments -> -f /usr/share/openocd/scripts/interface/stlink-v2.cfg -f /usr/share/openocd/scripts/target/stm32f1x.cfg
          • Click Apply. Run this tool once before each uploading-debugging session.

          DIY Temperature logger with STM32F103, microSD card and DS18B20.

          $
          0
          0
          The idea of the device I'm about to share with you (this may lead you to believe that I'm only going to share an idea, but I'm a tinkerer, not motivational speaker - scroll down for schematics and sources!) was born out of events completely irrelevant to microcontrollers or any technology whatsoever.
          Here's how it went down: the group of biology students was researching galls. Gall, they explained  to me in layman's terms, is an abnormal outgrowth on plant's leaves. They've been used for centuries to make ink and that's actually all they're known for. These students' research was aimed to find out if these galls really are so useless/malevolent in every case, or can even be beneficial (i.e. symbiotic) to their host.
          Typical gall. Taken from Wikipedia.

          To do that they needed to take periodic measurements of certain parameters in specific locations (e.g. humidity around the plant, temperature inside the plant etc..). They've figured all out, I've been told, but logging the temperature inside the gall. The device must be autonomous and its sensor must be tiny to fit inside. The nearest candidate they found was Maxim's temperature logging iButtons:

          IP67 autonomous temp. loggers. Can be bought in bulk for next to nothing and thrown around to know the temperature of EVERYTHING!

          Now, they are small and autonomous, but they were looking for something with even smaller sensor, something like this:
          Can be found  here, but for all intents and purposes it's unobtainium for mere students😃

          As it always happens, one thing led to another and I agreed to make a temperature-logging autonomous device for them with a tiny sensor (deciding to make a tutorial for a nice piece of hardware in the process).

          So, here's the tutorial on building a ready-for-customer temperature logger from scratch with inexpensive and easily obtainable parts:

          Part 1. Parts.

          The most important part-picking decision concerned temperature sensor. It has to be small and easily procured, right? Two choices that distinctly fit the bill immediately came to mind: thermocouples and DS18B20. IC temperature sensor is a lot bulkier than a droplet of two metals fused together, still, I picked DS18B20 after briefly considering the interface circuitry required for both:

          Interface between uC and temp. sensors: left - thermocouple, right - ds18b20. Roughly scaled against one another.

          The rest was easy to decide, so here goes:
          1. DS18B20 temperature sensor. You can get one in metal package, or a bare IC. I used the latter, because I hope to end up with something smaller than this steel cylinder after encasing it.
            DS18B20
            DS18B20 in waterproof package

          2. Blue pill. Inexpensive and versatile board with STM32F103C8T6 in its core.

          3. STLink v2 programmer. You'll need it to upload your code to STM32.

          4. microSD memory card + adapter for it. We'll convert microSD-SD adapter to microSD-microcontroller one. You can omit this part and just opt for an adapter board for microcontrollers (especially if you don't want to go further than a prototype) - less soldering, but maybe less fun.
            Adapter for microSD card.
            microSD adapter board for microcontrollers.

          5. Pushbutton, some jumper wires (these or these), one 4.7k resistor.

          6. For end product you'll additionally need:
          •  2 toggle or rocker switches (both SPST - one to switch operating mode and another as a power switch), and an enclosure-mount connector for temperature sensor. I used this circular 4-pin connector (something similar online can be found here):
            Left to right: power switch, mode switch.
            Body marking says XS9K4P.

            This connector is pure awesomeness. It looks like the plug is locked into place after being screwed into receptacle, but it is actually self-locking. You have to pull the outer 'collar' part of a plug to unlock it, otherwise it won't budge.

          • Coin cell battery. How big depends on what kind of autonomous time you expect to get from this logger, I'm using CR2477 (25mm diameter, 7mm height, 1Ah on average) to get as much as years. The standard CR2032 (20mm diameter, 3mm height, 220mAh on average) won't last as long, but it's encountered more frequently in daily life.

          • TODO

            Part 2. Prototyping.

            First off, some document links that might help:

            With a device as complex as this one (FAT filesystem access, temperature sensor access via SPI, real-time clock with battery backup), you gotta prototype before you start working on your device. Let's cobble up something that can read temperature and write it to memory card upon a click of a pushbutton - using only jumper wires! Why solder something as impermanent as this?

            That's the prototype

            Assemble it according to this schematic and connect STLink programmer:


            By the way, have you noticed something peculiar in this jumble of wires and electronics? I'm talking about SD adapter turned microSD-microcontroller interface with just a 2.54mm socket header:


            Got the idea for this gimmick from this blog post. It's not pretty, but still better than nothing in a pinch - certainly better than waiting for a slow boat to China to bring you an SD card adapter.

            Thanks you, Duncan the owner of  Shepherding electrons, for this clever and unconventional idea.

            What comes next is writing POC software for this thing. This proved to be unexpectedly challenging, in terms of firmware size.

            To write, upload and debug my code I used OpenSTM32 Workbench - an Eclipse-based IDE for STM micros. You can refer to my previous tutorial to learn how to set it up in Linux to debug and upload in one click.

            STM32F103C8T6 pack a hefty 64k of flash memory, and it looks like a whole lot of memory to someone with experience of programming 8bit microcontrollers in plain C or assembly code. In reality of 32bit and STM-provided libraries, merely including stdlib.h and time.h and using standard strftime function to pretty-print your datetime structure can eat up a whopping 10k of flash!

            Final prototype firmware that just logs temperature to SD card every 2 seconds as soon as the button is pressed is sized about 57k  - and the final device will require much more code! The OpenSTM32 project for prototype can be downloaded here.

            Upload it, wait for 2 quick blinks of onboard LED. Then, press the button on PB11, the LED will blink rapidly as soon as the press is 'seen' on microcontroller (yes, I f*kken love to blink LEDs). Release the button and temperature logging will start with the period of 2 seconds.

            To end logging process, press the button again until you see rapid blinks. Actually, ending the logging process properly is really important - unplugging memory card or powering off your device in the middle of write operation can lead to complete obliteration of FAT filesystem.

            Logged temperature is recorded in tab-separated files (.csv, though technically it's not a space-separated file) and can be accessed after just plugging your memory card to a card reader on your PC:

            Each log file is marked with creation date - it's year 1970 because I didn't set up RTC counter.

            You can import CSV files into any spreadsheet program - just make sure to pick Tab as the only record-separating symbol. Each log entry has a timestamp against it.

            CSV file is easily imported into any spreadsheet software.

              Part 3. Real device.

              There are several things to consider about our end device, and flash size is one of them.

              All the code that you write is placed in flash memory which is 64kB on Blue pill, and prototype's code nearly depleted this limit. Keeping in mind that prototype lacks a couple of vital functions that I had in store for the real device, I naturally expected that I'll have to cut memory consumption wherever I can to stay within 64k.

              Another thing is power saving. I settled on a plan to measure the current consumption in the prototype first, just to get a sense of the order of magnitude of power-saving works. To have that ready I only did two things: desoldered power-indicating LED from Bluepill and improvised a current-measuring jig like this:


              Prototype's code would hog up around 7.5mA during temperature reading and SD write operations, and a whopping 5.5mA when it's just waiting!

              Current consumption while measuring and writing to SD.
              Current consumption during waiting.

              According to this battery life calculator that's only about 30 hours of uptime if it's powered from CR2032 (remember, one of the most important goals was to build a miniature device).

              Average CR2032 capacity is 200-240mAh.

              Logger will spend most of the time waiting to make a measurement (specifically my 'customers' wanted to measure temperature twice a day), hence the current consumption we want to minimize is idle time consumption.

              STM32F10x value line controllers come equipped with 2 modes for moderate to extreme power saving - STOP and STANDBY mode. To read more about those, refer to STM32F10x reference manual here .

              Let's now upload some code to see how much we can save during idle time:
              • STOP mode:
                milliamps here, barely legible
                That's nice! But let's see if we can do even better...
              • STANDBY mode:
                microamps
                Awesome! More that two-hundredfold decrease in current consumption compared with no power saving! Incidentally, our microcontroller can wake up from this mode with RTC interrupt, which is exactly what we need.
              Let's check our battery life calculator again:

              A little over 8 month of work on CR2032 cell, provided it's not waking up too often.

              Eight month is just great for just about any autonomous device! However, I wanted the user to NEVER ever face the need to remove the cover and change the battery, so I went for a bigger battery CR2477(25mm diameter, 7mm height, 1Ah on average) compared to CR2032 (20mm diameter, 3mm height, 220mAh on average). That increased device's lifetime to 3.3 years approximately.

              How to create a Spring Boot web application using Intellij IDEA Community Edition

              $
              0
              0
              Hello! This blog post focuses on one simple task: quickly creating a web application using Spring Boot in IntelliJ IDEA Community Edition.

              For those having EAP or Ultimate version installed, you may refer to this tutorial that takes the built-in Spring Initializr project creator into account. The less fortunate folks (like me) will have to do slightly more work, but will also benefit from learning  the nitty-gritty of spring-based projects and maven. And, to be fair, that's not much more work than using the Initializr plugin in advanced IntelliJ versions.

              There are two approaches to making a Spring Boot project. One of them is using Spring Initializr web application to generate your project template, which is supposedly easier, and another is manually adding the dependencies into your barebone Maven project.

              Personally, I found that both approaches take about the same amount of time, so pick any one of them - it won't siphon more your precious time. To use the former approach, start from step 1, if you'd like the latter you may skip to step 4 immediately.

              Let us begin, then!

              Step 1. Create a maven project

              • It all starts with a project. Create a new project on Welcome screen:
               
              •  Pick Maven from type list. Click Next.
              •  Now you'll have to come up with GroupId and ArtifactId for your project. Refer to this page from Maven guide to learn about this. Generally, GroupId is your (or your company's) web domain in reverse. If you don't have one, just use your name or nickname, i.e. com.johndoe . ArtifactId is the name of your project.
              •  Pick your project's name and location. I usually name my projects just like ArtifactId to avoid confusion.
              •  That's it! You have your project now. Why's it have Maven type? Because it, first of all, it allows you to easily pull any kind of dependency into your project by just typing its GroupId and ArtifactId, and secondly it creates your project with well-defined folder structure that is considered de-facto standard for Java apps. You can learn more about it here.

              Step 2. Add Spring boot dependencies

              •  Paste those to your pom.xml and enable dependency auto-import to avoid the fuss of continuously reimporting dependencies each time you add, remove or change one.

              Step 3. Create a minimal set of classes

              • Now that we have our libraries, we're going to need to create a minimally viable code to make those libraries work. First of all, you want to conform to the maven directory convention and create a package in src/main/java named after your groupId.
              • Now, Spring Boot launches Tomcat servlet container and your application when you launch this method:
                public static void main(String[] args) {
                Let's create a class containing one:
              • Paste this code snippet into your new class: Don't forget the @SpringBootApplication annotation! It makes it all tick...
              • As you must have noticed, the dependencies have not been added yet:


                To import the dependency automatically, center your mouse on the red-colored class name and press Alt+Enter:

              Step 4. Use Spring Initializr

              Spring Initializr usage in pretty straightforward - you navigate to the website, set up your project details and get a Zip archive upon clicking the big green "Generate" button.

              Unpack it someplace and that's what you're supposed to see:

              Step 5. Import the generated project into IntelliJ IDEA

              • Instead of creating a project, click Import project now.
              • The first two steps are important: you're supposed to point to your unzipped folder and pick Maven as your import's model.

              What comes next is essentially clicking Next until you get your new project imported to IntelliJ IDEA. Yeah, it's as simple as that.

              Step 6. Create a launch configuration

              • Let's create the launch configuration to start our application. First, click Edit configurations...
              • Create a new configuration of Application type. Name it and pick your class containing main() method to launch:

              • And that's actually all. Click the Run button (alternatively, press Shift+F10). You'll see that your app has started on URL http://localhost:8080 in build output window:

              To make sure it works, though, you might want to make it a bit interactive...

              Step 7. (Optional) Add at least one controller

              • Create a new package for your controllers under your groupId package, along with a new class for controller:

              As per usual, the complete project can be found HERE.

              Addendum

              Just for the sake of completeness, I'll show how to add any kind of dependency into your Maven project. You don't have to do it to create your Spring Boot app, but it helps to know where to start in your development.
              1. Search <your library name here> maven.
              2. People mostly pick either the latest stable version (5.0.0 in this case) or the most used one.
              3. Copy the text to your pom.xml, specifically the <dependencies> section.

              Netflix microservices stack, part 1: Feign

              $
              0
              0
              At my job I was recently tasked with investigating the possibility of separating our monolithic web-application into services (I'm a Java developer BTW). Obviously, we couldn't just break our huge back-end application into a swarm of microservices in reasonable time, that's why the focus of my research lay in gradual transition to service-based architecture. It may sounds hard, but not insurmountable anymore!

              Quite surprisingly, during my furious googling(hehe) I found that the giant of cloud-based streaming media services, namely Netflix, has open-sourced its framework of microservice tools.

              I managed to learn two things in the course of my investigations: microservice architecture is infinitely scalable and simple and that there's not nearly enough example-backed reading material on the Internet on the subject of using Netflix microservices on Spring Cloud without Eureka (which is responsible for service discovery).

              So in these series of blog posts, I'm going to try and enlighten the reader on the subject of Netflix microservice stack, beginning with Feign - the declarative REST client library. Then I'll follow up with the post on the hot topic of adding client-side load balancing with Ribbon (with hard-coded services at first), and hopefully there will even be the third post with dynamic service discovery using Eureka.

              Some theory beforehand

              Before lunging head-first into a completely new area of expertise, it helps to read up on the subject. I'll share my personal favorite reading list for microservice-related stuff:
              Feign is the first stepping stone of implementing microservice architecture with Netflix tools. In the reality of loosely-coupled services, lightweight and simple to debug communication is the key. That is why REST is often the communication of choice, even if sometimes it's not the best choice possible (take a look at this and this for details). That's where we'll use Feign: it will consume the messages from other services and convert them into Java objects.

              Practice time!

              First of all, let's create a Spring Boot application for our client. That's not strictly necessary, but it makes for easy configuration, and Spring Cloud Feign starter (what's a starter?) that we will use pulls Spring Boot as a dependency anyway.

              If "create a spring boot application" doesn't sound straightforward to you, you can follow this tutorial to do it. Don't worry, it's a breeze.

              Add feign starter dependency into your pom.xml (<dependencies> section):

              Now's the best time to decide what kind of REST API are we going to consume. For the sake of completeness, I'll demonstrate the whole range of CRUD operations in this example. Now, only the last piece of this puzzle is  missing: who is going to provide us with a RESTful service conforming to a given specification? There are free to use websites that do just that: expose a fully-defined REST API for testing purposes. I found at least two services like this: ReqRes and JSONplaceholder:

              ReqRes and JSONplaceholder provide a complete REST API to test our Feign app.

              Feign uses interfaces annotated with @FeignClient to generate API requests and map responses to Java classes. Let's first compile a list of API calls:

              ActionHTTP MethodURL
              (C) Create a userPOSThttps://jsonplaceholder.typicode.com/users
              (R) Get a list of usersGEThttps://jsonplaceholder.typicode.com/users
              (R) Get one userGEThttps://jsonplaceholder.typicode.com/users/{id}
              (U) Update user detailsPUT or PATCHhttps://jsonplaceholder.typicode.com/users/{id}
              (D) Delete a userDELETEhttps://jsonplaceholder.typicode.com/users/{id}

              Now we can create model classes and an interface to describe REST API to Feign:
              • Add a dependency for Jackson - JSON (de)serializer. Feint will use it to handle JSON in HTTP requests and responses.
                (Optional) Add Lombok dependency to pom.xml.
                Lombok automatically generates the boilerplate code associated with POJOs (getters, setters, constructors). You can skip this, but you'll have to write getters/setters for your model classes manually.
              • Create model classes in model package under root package.
              • Create Feign client interface in feign package under root package.
              • Create a controller with Feint client invocation, just to make sure it works. Here's what each of those lines do:

                .contract defines what annotations and values are valid on Feign interfaces. Specifically, with SpringMvcContract() we can annotate our client methods with Spring annotation @RequestMapping. Without this you'd get UnsatisfiedDependencyException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userClient';
                .encoder and .decoder will allow Feint client map JSON to Java objects and back,
                .logger and .logLevel will log each request and response to System.error. Convenient for create, update and delete calls where you can't exactly tell if it works or fails silently.,
                .target is pretty much self-explanatory. That's where our application will send its requests and receive responses.

              • Launch your application, go to http://localhost:8080/read.
                Looks like we can connect and get the list of users! You may take a look at the console window in your IDE to see the details of HTTP communications:
              That was the absolute minimum you need to know about using Feint with Spring Cloud.

              If you'd like to check out how other methods (create, update, delete) work and learn how to exact UserClient to a bean instead of creating it manually in every class where you need it, I'll be glad to continue my rant😊

              Imagine a real-world application with at least 50 classes in it. Let's say about 20 of them use our UserClient for authentication. You think writing Feign.build().... in each one of them is painful? Think about change of communication from JSON to XML! That's where the wonderful Spring Beans will save the day. Before we start with checking other CRUD methods, let's turn UserService into a bean:
              • Create a configuration class for Spring context in a new config package under root package.

                Under /src/main/resources create an application.properties file with a single line:
              • UserService can be autowired into any class. The controller class can be rewritten to include other CRUD methods and a simpler autowired UserService:
              • If your application starts now, that means autowiring works its wonders. At last, you can try each method out in your browser:

              Thank you for following the guide all the way through. Stay tuned for part two, where we'll add Ribbon load balancing with hard-coded list of services!

              As usual, the project can be found here: GitHub

              Как создать Spring Boot веб-приложение в Intellij IDEA Community Edition

              $
              0
              0
              In English

              Всем привет! В этом посте мы сосредоточимся на одной простой задаче: быстро создать веб-приложение на Spring Boot в IntelliJ IDEA Community Edition.

              Те, у кого установлена версия EAP или Ultimate, могут обратиться к этому мануалу, который учитывает встроенный в IDE создатель проекта при помощи Spring Initializr. Менее удачливым людям (например, мне) придется сделать немного больше, но при этом мы узнаем немного больше о создании проектов при помощи Spring Boot и Maven. И, честно говоря, это не намного больше, чем использование Initializr в крутых версиях IntelliJ.

              Существует два подхода к созданию проекта на Spring Boot. Один из них - использовать веб-приложение Spring Initializr для генерации шаблона проекта - это по-идее проще, а другой - вручную добавить зависимости в пустой Maven-проект.

              Лично я думаю, что оба подхода занимают примерно одинаковое количество времени, поэтому выбирайте любой из них - он не потратит кучу Вашего драгоценного времени. Чтобы использовать первый подход, начните с шага 1, а если вы хотите использовать второй, то можно сразу перейти к шагу 4.

              Ну что ж, начнем!

              Шаг 1. Создаем maven-проект

              • Все начинается с проекта. Давайте создадим его на приветственном экране Intellij:
               
              •  Выберите Maven из списка типов проектов. Щелкните Next.
              • Теперь надо придумать GroupId и ArtifactId для проекта. Смотрим эту страницуиз официальных мануалов Maven чтобы узнать как их выбрать. Обычно GroupId это Ваш (или Вашей фирмы) домен в обратном порядке. Если нет ни того, ни другого - не проблема, используем имя или ник, например com.ivanivanov. ArtifactId - имя проекта.
              • Выбираем имя проекта в IDE и где он будет находиться на жестком диске. Я обычно выбираю имя проекта такое же как ArtifactId чтобы не было путаницы.
              • Вот и все! Проект готов. Почему мы используем Maven? Во-первых, это позволит нам подтянуть любую зависимость просто введя ее GroupId и ArtifactId, во вторых в таком проекте автоматически создается очень удобная структура папок которая является де-факто стандартов для Java приложение. Почитать об этой структуре можно тут.

              Шаг 2. Добавим зависимости Spring boot

              • Вставляем их в файл pom.xmlв корне проекта и включаем авто-импорт зависимостей чтобы не жать кнопку Импорт при каждом изменении помника.

              Шаг 3. Создаем минимальный набор классов

              • Теперь, когда зависимости подключены, понадобится создать минимально жизнеспособный код, чтобы все эти библиотеки работали. Прежде всего, последуем бест практисами создадим корневой пакет в каталоге src/main/java, названный именем проекта.
              Имя пакета должно быть com.shortn0tes.springbootapp. Что ж, все ошибаются...
              • Spring Boot запускает сервлет-контейнер Tomcat и Ваше приложение при запуске этого метода:
                public static void main(String[] args) {
                Так создадим класс в котором он будет содержаться:
              • Вставьте этот код в новый класс: Не забываем аннотацию @SpringBootApplication! Благодаря ней все и работает.
              • Как уже видно, названия классов подсветились красным потому что они не импортированы:


                Чтобы автоматически импортировать зависимость на класс в IntelliJ IDEA, щелкните на красном имени класса и нажмитеAlt+Enter:
              • Вот и все! Минималистичное Spring boot приложение готово. Теперь можно пройти к шагу 6

              Шаг 4. Используем Spring Initializr

              В использовании Spring Initializr все просто и понятно: заходим на сайт, настраиваем проект и получаем Zip архив по щелчку на гигантскую зеленую кнопку "Generate".

              Куда-нибудь распаковываем его и видим следующее:

              Шаг 5. Импортируем сгенерированный проект в IntelliJ IDEA

              • Вместо создания проекта, кликаем на Import project.
              • Первые 2 окна важны: нужно указать куда был распакован проект и указать Maven в качестве модели импорта.

              Дальше просто щелкаем Nextпока проект окончательно не импортируется. Да, все так просто.

              Шаг 6. Создаем конфигурацию запуска

              • Чтобы запустить наше Spring Boot приложение, надо создать конфигурацию запуска. Щелкаем Edit configurations...
              • Создаем новую конфигурацию типа Application. Называем ее как-нибудь и выбираем наш класс с методом main():

              • Вот и все. По щелчку на Run (или сочетанию клавиш Shift+F10) увидим что приложение Spring boot запустилось на http://localhost:8080:

              Чтобы удостовериться что оно работает, придется сделать его несколько более интерактивным...

              Step 7. (Опционально) Добавим как минимум 1 контроллер

              • Контроллеры - это часть архитектурного паттерна MVC. Spring позволяет запросто создавать контроллеры для веб-приложений, навешивая аннотации на класс с методами. Создадим новый пакет для контроллеров в корневом пакете, а также класс для нового контроллера:
              Spring boot при запуске сам просканирует корневой пакет (т.е. тот в котором находится класс с аннотацией @SpringBootApplicationи методом public static void main()) и внесет все бины, включая наш новый контроллер. Теперь можно запустить приложение и увидеть что оно работает:


              Как всегда, готовый проект можно скачать ТУТ.

              Дополнение

              Для полноты рассказа покажу, как добавить любые зависимости в Ваш проекта при помощи Maven. Это необязательно для создания Spring Boot приложения, но это поможет понять начинающему, что делать дальше.
              1. Ищем <имя библиотеки> maven.
              2. Обычно все выбирают либо последнюю стабильную версию (5.0.0 в данном случае) либо самую используемую.
              3. Копируем текст в pom.xml, а именно в секцию <dependencies>.

              Микросервисы с Netflix, часть 1: Feign

              $
              0
              0
              In English

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

              В результате яросного гугления (хихи) к своему удивлению я узнал, что гигант стриминга фильмов и сериалов из США, а именно Netflix, полностью открыл код своего микросервисного стека.

              Вот что я узнал пока почитывал про все это: микросервисная архитектура отлично масштабируется и проще в отладке и изменении кода а также то, что в Интернете очень мало гайдов с примерами использования микросервисов Netflix на Spring Cloud без Eureka (которая ответственна за построение регистра сервисов).

              Поэтому в этой серии постов я постараюсь пролить немного света на стек микросервисов от Netflix, начиная с Feign - библиотеки для создания декларативных REST-клиентов. За ним последует пост на горячую тему балансера нагрузки  Ribbon (с хардкоднутым списком сервисов), и, надеюсь, еще хватит сил на третий пост о добавлении в эту связку динамического списка сервисов при помощи Eureka.

              Немного теории

              Прежде чем начинать работать с полностью новой технологией, неплохо бы почитать на эту тему. Вот составленный мной список полезных ссылок по микросервисам на Netflix:
              Feign - это первый шаг в реализации архитектуры микросервиса тулами Netflix.В реальности слабо связанных сервисов очень важно чтобы общение между ними было легковесным и простым для отладки. Поэтому для этой цели зачастую используют REST, хотя для некоторых случаев это может быть не лучшим выбором (смотрим, например, дискуссии на эту тему тути тут). Для упрощения связи по REST мы и используем Feign: при помощи него мы будем поглощать сообщения от других сервисов и автоматически превращать их в Java объекты.

              Практика!

              Начнем с того, что создадим для нашего REST клиента Spring Boot приложение. Это не то чтобы обязательно, но Boot упрощает конфигурацию и запуск, да и Spring Cloud Feign starter (что такое стартер?) которой мы будем использовать все равно подтягивает Spring Boot в качестве зависимости.

              Если "создадим spring boot приложение"не звучит супер просто, то можно воспользоваться этим туториалом. С ним Вы научитесь этому делу буквально минут за 10.

              Добавим зависимость от feign starter в наш pom.xml (секция <dependencies>):

              Теперь нужно понять, где взять REST API из которого будем брать данные. Для полноты демонстрации в этом примере мы потестим все CRUDоперации. Так где же взять такой API, который будет соответствовать нашим требованиям? Как ни странно, в существуют бесплатные веб-сайты которые делают именно то что нам надо: предоставляют простой REST API для тестирования. Я нашел 2 таких: ReqResи JSONplaceholder:

              ReqRes и JSONplaceholder предоставляют полноценный REST API чтобы мы могли потестить наше Feign приложение.

              Feign использует интерфейсы аннотированные @FeignClientчтобы генерировать API запросы и мапить ответ на Java классы. Давайте сначала составим список вызовов к выбранному нами REST API:

              ДействиеHTTP методURL
              (C) Создать пользователяPOSThttps://jsonplaceholder.typicode.com/users
              (R) Получить список пользователейGEThttps://jsonplaceholder.typicode.com/users
              (R)Достать одного пользователяGEThttps://jsonplaceholder.typicode.com/users/{id}
              (U) Обновить детали пользователяPUT or PATCHhttps://jsonplaceholder.typicode.com/users/{id}
              (D) Удалить пользователяDELETEhttps://jsonplaceholder.typicode.com/users/{id}

              Теперь можно создать модели и описать вызовы REST API Feign'у:
              • Добавить в список зависимостей Jackson - сериализатор/десериализатор JSON. Feint будет использовать его для HTTP запросов и ответов.
                (Опционально) Добавить в список зависимостей Lombok.
                Lombok автоматически генерирует стандартные геттеры/сеттеры/конструкторы для POJO. Можно не добавлять, но тогда придется писать весь boilerplate самому.
              • Создадим модели в пакете modelпод корневым пакетом.
              • Создадим интерфейс клиента Feign  в пакете feignпод корневым пакетом.
              • Создадим контроллер с вызовом клиента Feint, просто чтобы убедиться что все работает. Детальное описание что делает каждая строка:

                .contractопределяет какими аннотациями мы будем метить Feign интерфейсы. А именно, благодаря SpringMvcContract() можно использовать спринговые аннотации @RequestMapping. Без этого получим UnsatisfiedDependencyException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userClient';
                .encoderи .decoderзаставят Feint клент мапить JSON в Java объекты и обратно,
                .loggerи .logLevel - логировать каждый запрос и ответ в System.error. Очень удобно для операций create, update и delete - чтобы понять, сработали они или тихо зафейлились,
                .target - в общем и так понятно. Сюда наше приложение будет слать запросы и получать ответы.

              • Запустите получившееся приложение. Теперь заходим на http://localhost:8080/read.
                Сработало! Получается соединиться и получить список юзеров. Можно также обратиться в консоль или окно консоли в IDE за деталями HTTP  коммуникаций:
              Это был абсолютный минимум который надо проделать, чтобы попробовать Feint в Spring Cloud.

              Если Вам хочется посмотреть как работают другие методы (create, update, delete) и узнать как извлечь UserClient в бин вместо того чтобы создавать его каждый раз когда он понадобится, буду рад продолжить повествование😊

              Представим себе настоящее приложение, в котором точно есть как минимум 50 классов. Скажем, около 20 из них будут использовать UserClient для аутентификации. Думаете, писать в каждом классе Feign.build().... - это боль? Тогда подумайте о вполне вероятном сценарии смене транспорта с  JSON на XML! Вот здесь очень помогут замечательные бины. Прежде чем начать реализацию остальных CRUD методов, превратим UserService в бин:
              • Создадим класс с конфигурацией для контекста приложения Spring в пакете configпод корневым пакетом.

                В каталоге /src/main/resources надо создать файл application.properties с одной-единственной строкой:
              • Теперь UserService можно автовайритьв любой класс. Теперь можно переписать контроллер, чтобы он включал в себя все CRUD операции и намного более простой автовайреный UserService:
              • Если теперь приложение запустилось без ошибок, то автовайринг уже творит свою магию. Наконец, можно опробовать каждый метод при помощи браузера:

              Спасибо за то что дочитали до конца! Скоро появится часть 2 этого поста, где мы добавим балансировщик нагрузки Ribbon с захардкоженным списом сервисов!

              Как всегда, полный код проекта можно найти тут: GitHub

              Netflix microservices stack, part 2: Feign+Ribbon

              $
              0
              0
              Netflix microservices stack tutorials:
              Hello again! Following up on the previous post about Netflix Feign (REST client),  here goes the next post on Ribbon - the load balancer.

              Most tutorials that teach how to incorporate load balancing using Ribbon describe how to do it with an additional service discovery application, usually Eureka. In this scenario, each additional microservice announces itself to Eureka, and Eureka proceeds with dynamically forming the list of available microservices and probing each microservice's status individually to cross it out from the list when it's dead. Ribbon distributes the requests between microservices based on the list from Eureka.

              This tutorial will focus on Feign-Ribbon bundle exclusively. We'll add Ribbon-powered load balancing capability to our Feign client, but the list of services is going to be declared statically. This is suitable for some cases where you just need load balancing without the additional fuss of setting up service discovery.

              Get yourself a Feign client

              In this tutorial we're going to build on top of the previous one, the one where we created a Feign client that consumes JSON data from the REST API testing service, so if you already followed that, just skip to the next step. If you've just started reading this, you may just clone my repo containing the full project.

              Make a REST API service

              Now that we've decided to start switching between our services, one online service is not enough. We'll have to make our own user service with the same REST API that will adhere to the same contract as the online service from part one.

              If you want to learn how to make a REST API service, read on. Or you can just download it from my repository (link), launch runServices shell script (located in user-service directory) that will start two instances of User Service on ports 8090 and 8091. Those are the instances we will use for load-balancing.

              Detailed walkthrough of creating a REST API service:
              • Create a new Spring Boot application.
              • We don't want any extra work, so let's just copy the models over from the previous Feign tutorial where we created a REST client with Feign to consume data from online REST API service:
                Same models = same API contract = no changes needed in Feign client!
              • Since we're going to generate user data from scratch, we're going to add one more dependency for Apache Commons text library to generate random Strings easily.
                With that library in our classpath, we can add randomize() function to our models:
              • The controller that'll have all the CRUD operations for User model can be easily implemented now:
                As you must've noticed, I'm using the LOGGER object to indicate that this particular instance of user service was used, as we'll be launching more that one. To do that, I added one more dep for SL4J logging framework:

              • The REST API service is ready. Launch the application and make sure it works:
              • Now, purely for convenience, I wrote a shell script to launch 2 instances of this user service to balance between:

              Add Ribbon load balancer to our Feign client

              As promised, we're not going to build from the ground up. If you followed my previous tutorial, you'll have to modify the client we built in it:
              • In Config.java: add two new annotations to the class to enable Ribbon and change the target type:
                This will connect the client to the named load balancing target that Ribbon will create (http://targetname)
              • In UserController.java: load Ribbon configuration from .properties file
                ... and reduce userClient invocations to one per one endpoint, to make API calls easily traceable.
              • In UserClient.java: just add one more annotation - @FeignClient("user-client")
              • Rename application.properties to ribbon-client.properties, and replace its contents: Eureka is enabled by default when using Ribbon, so we'll have to explicitly switch it off. The second line creates the load balancing target named "user-client" with two hard-coded instances (syntax for this configuration can be found here).
              • Add two new deps into pom.xml: Archaius just configures Ribbon with what we specified in .properties file. Normally, when used with Eureka, this is done automatically, but given that we've omitted Eureka completely we'll have to do it all manually.
              The client can be launched now and the default Round-Robin algorithm of balancing can be seen in action:

              Solr 7 beginner tutorial: dataimport from PostgreSQL database

              $
              0
              0
              This tutorial was written for beginner Java developers and is meant to quickly set you up with Solr.

              As such, it covers the following subjects: installing Solr, creating and configuring a core, setting up dataimport handlers to import documents from database, Java coding.

              As usual, I'll try my hardest to make it example- and practice-driven, considering you can read all theory on the matter of Solr i.e. here:

              So, here's what we'll do: first, we'll install a database and import lots of sample data.

              Why? You can import documents (basic entities in Solr, compared to RDBMS those would be rows in table) to Solr from a multitude of sources, but the most popular use case is to store text data  (i.e. blog posts) in traditional database and import it to Solr to allow for quick search. Solr's index will really shine in scenarios where you want to do multi-criterion search (i.e. I need a book with title like this and this year of publishing that was published in Norway). Here's a nice link that describes key differences between traditional RDBMS index and Lucene index (which is a search engine underlying Solr).

              Then we'll install Solr and create a core for our collection of sample data, define its schema (i.e. fields and their types and so on) and write a custom data import handler. The outcome of all this labor is that we'll be able to simply navigate to http://localhost:8983 and import thousands of documents from database upon a button click.

              This tutorial assumes Arch Linux or some other Linux distribution is installed on your PC. You can do it on any other operating system though, it's just easier this way. To Windows users like me I'd recommend installing Oracle's VirtualBox and importing one of the many Arch-based distros, like Manjaro.

              Log in screen of fresh Manjaro 17 VM

              Log in with password osboxes.org. Let's kick off our session!

              Database

              I thought I'd give PostgreSQL a try, since it's the only RDBMS I've heard of in positive context. The installation is dead-simple, though initial configuration can be quite daunting if it's you first time with Postgres. I referred to Arch Wiki for setup recommendations. Open up the console (Terminal is the application's name)

              Now that the database is set up, we can grab and import some kind of data for testing purposes. What I found after a couple of minute's worth of Google trawling is AdventureWorks Database - a Microsoft product sample for an online transaction processing (OLTP) database. The AdventureWorks Database supports a fictitious, multinational manufacturing company called Adventure Works Cycles.
              Some nice person even uploaded a set of scripts that can import this to PostgreSQL -> here.
              First, you'll have to download the original OLTP database from the link on the page I linked. Then clone the repository to your home directory:
              All the contents of OLTP script archive have to be extracted to AdventureWorks-for-Postgres directory:

              Now, launch the data transformation and importing scripts. You'll have to create a user with the same name as your UNIX user to allow importing from files in your home directory.
              The huge collection of all sorts of entities is imported to PostgreSQL database Adventureworks. There's employees, transactions, orders and much more.
              Let's check it out:
              One thing worth noting is the schema of the table we're going to use for import. If you're familiar with definition of schema in databases, Solr structures the data according to schemas just like Postgres. We'll have to know the schema of any dataset we'll want to import to Solr. The schema of the table person.person we'll use later can be found below:
              We can get to the point now and install Solr.

              Solr

              Installing and creating a core

              Download and unpack the latest version of Solr. At the time of writing this tutorial the latest version was 7.2.1. After unpacking it (to your home directory, for example) you'll have a fully functional full-text search engine ready to go:


              What do those directories contain?
              •  /bin contains Solr executable.
              • /server/solr contains the cores.
              • /dist contains JAR libraries designed to enable extra features in Solr.
              • /contrib holds the additional files for the libraries mentioned above.  Namely, /contrib/{featureName}/lib contains the additional libraries needed to add this feature (i.e. JDBC driver lib for data import feature).
              • when in doubt about organizing your Solr collections, take a look at /example directory. Examples are made according to best practices.
              Time to start examining the subject of cores. lsof program is additionally needed on Solr startup to determine if it's up or not.
              Let's create a core to hold all the employees in Adwentureworks company: You can access your local Solr instance on http://localhost:8983/solr/
              Note the 'data driven schema' warning. It refers to Solr's ability to infer the schema of collection (collection is synonymous with core in our one-server setup, read more about it here). If we were to simply continue using our core, the schema for the adwentureworks_person core (i.e. a set of fields each document has, their types and so on) would be determined at run time upon adding new documents. For instance, after creating a core we could add a new person to it (no need to actually do it, this is just an example): Solr would infer that collection adwentureworks_person requires fields "id", "name" and "title" typed number, text and text correspondingly, and add those fields to the schema. Looks convenient!... but this approach is rarely used in production as the schema is the blood contract between data layer and backend app.
              That's why we'll disable this feature: We can get to the schema part of our tutorial now.

              Schema 

              Schema is the first thing we're going to configure in our collection. Schema defines:
              • what fields can document have,
              • which ones of them are mandatory,
              • what types do they have 
              • and how to perform indexing and searching on each of those documents.
              The schema for our core is located in /server/solr/adwentureworks_person/conf/managed-schema. It used to be named schema.xml in old Solr versions, but introduction of Schema API (this is a must-read link) added a new type of schema, the managed schema, that can be edited at runtime via HTTP requests remotely.

              For detailed explanation of Schema editing interface, see here. If you ever decide to edit you schema on the go without messing with config files, you'll need this.

              Schema API also made editing fields from your browser possible! Like this:

              Back in the days when Schema API wasn't introduced yet, you had to manually connect to server running Solr, rummage around the hard drive to find schema.xml and type in new fields/change existing fields. That's what most tutorials around the Internet suggest you do, in fact.

              This tutorial will go the novel way, so we're going to configure the schema from browser entirely.

              Now, as for the field types and properties, the official Solr manual (you should read this one, too) has the most concise description, as usual.

              The most essential field types are as follows:
              • text_general: use it for all kinds of normal text data (i.e. names, addresses, book titles etc.)
              • string: use it for text that you don't want tokenized, for example, IDs.
              • pint, pints, plong, plongs: integer and long types (signed 32 and 64 bit respectively).
                p stands for pointer - meaning the internal Solr representation of number will allow for faster searching.
                s postfix means the field is multivalued. (Have you read the link from the paragraph above yet? Then you know what multivalued means.)
              • pfloat, pfloats, pdouble, pdoubles: 32- and 64-bit IEEE float and double types.
              • boolean: equals BoolField. As quoted from Solr docs: Contains either true or false. Values of 1, t, or T in the first character are interpreted as true. Any other values in the first character are interpreted as false.
              Here's the full list of all types that are shipped with Solr 7: link.

              Enough theory, let's create our own schema now! I'll show how to add only two fields from Postgres person.person schema: firstname and lastname. You can add all of them, if you'd like.
              1. Create a stored, indexed and required firstname field.
              2. Rinse and repeat for lastname
              3. There already exists an ID field, so we don't have to create another one:

              That's all! You can check your managed-schema and see the fields you just added:
              No need to restart Solr, the changes were applied immediately.

              Data import.

              Unfortunately, no one from Solr team thought of implementing data import handler editing from the browser, that much can be gleaned from the bare page of dataimport:

              To get our table data into Solr, we'll finally have to edit some files.

              1. But first, you'll have to download PostgreSQL JDBC driver (postgresql-version.jar, I used postgresql-42.2.0.jar) and move it to contrib/dataimporthandler/lib/ (you'll have to create lib folder):
              2. Edit your solrconfig.xml in server/solr/adwentureworks_person/conf/ : insert the following lines there:
              3. Create a file named data-config.xml (as defined in the previous step) in server/solr/adwentureworks_person/conf/ directory with these contents:
              4. Make sure dist/ directory contains libraries for dataimport: solr-dataimporthandler-version.jar and solr-dataimporthandler-extras-version.jar
              5. Restart Solr:

              The Web interface will contain data import section. Click Execute and voila!

              If your import query finishes immediately, something is wrong. Double-check you configuration and restart Solr.

              You can refer to detailed docs on data import in Solr here.

              Let's perform a test query. If import worked, we'll see plenty of data:

              Java.

              Initially, I wanted to include Java samples in this post, but since it's already enormously long I'll leave it for the next part. Stay tuned!

              Инструменты начинающего электронщика

              $
              0
              0
              Привет! Эта статья - приложение к видео на моем канале:


              Описание из видео:

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

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

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

              Можно попробовать рискнуть и взять самое дешевое. Я знаю людей разочаровавшихся в электронике именно из-за постоянной фрустрации во время работы с кривым инструментом.
              Разумеется, также не хочется тратить сотни тысяч на оборудование для хобби, которое можешь забросить от скуки.

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

              Паяльное оборудование

              Паяльники

              Паяльник с регулировкой температуры


              Ссылка
              Рекомендации по выбору: можно взять самый дешевый из паяльников с регулировкой температуры. Отличительная особенность - колесико или еще какой-то способ настраивать температуру. Шнур у этого паяльника довольно короткий, поэтому я брал такой же с американской вилкой (просто он был дешевле), отрезал ее и припаивал на ее место более длинный шнур с правильной вилкой.

              Паяльные станции

               Lukey 852D+FAN

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

              Сейчас она уже подорожала и не везде ее купишь, поэтому сейчас лучше купить что-то из того что я подобрал пониже:

              Yaogong 8586


              Ссылка
              Самая оптимальная по отношению цена/качество для новичка, имхо. Стоит в 2 раза дешевле чем моя Lukey, тем не менее фен и паяльник там те же, только сама станция более миниатюрная.

              PJLSW 8586



              Ссылка
              То же что выше, но даже еще дешевле. Можно рискнуть и взять, если очень сильно хочется станцию но не хочется тратить много денег. К тому же, чиня станцию получишь незаменимый опыт! 👆

              Газовый паяльник

              Ссылка
              В первое время будет не нужен, но все же очень удобно когда можешь паять где угодно. Стоит взять если, например, собираетесь участвовать в соревнованиях по робототехнике.

              Заправляется как обычная зажигалка, тем же самым жидким газом в баллоне. Чем больше обьем баллона - тем на дольше ее хватает, я взял себе самый большой баллон из всех что нашел тогда.

              Аксессуары

              Жало "скошенный конус" 900M-T-2C

              Ссылка
              Рекомендации по выбору: не брать жала оранжевого цвета - они медные без антикоррозийного покрытия. Через месяц активной пайки такое жало просто исчезнет.
              2C означает диаметр жала 2мм. Еще есть 1C-5C, но для большинства работ мне хватает именно 2C. Иногда, впрочем, для больших работ очень пригождается жало 4C.

              Жидкий флюс ЛТИ-120

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

              Жидкий флюс Ф-38Н

              Ссылка
              Адская смесь, которая подойдет даже для пайки алюминия. Я пускаю ее в ход когда флюс выше не работает.

              Припой

              Ссылка
              Самые часто используемые припои ПОС (припой оловянно-свинцовый) состоят из олова и свинца, и цифра после ПОС - процент содержания олова. Чем больше олова-тем выше цифра-тем легче плавится припой-тем легче с ним работать. Возьмите ПОС-63, но если его нет то и ПОС-61 тоже подойдет.

              Припои есть с канифолью внутри и без. Я всегда беру без - самому флюс наносить удобнее.

              Канифоль


              Ссылка
              Рекомендации по выбору: Нет смысла покупать гигантскую банку. За 5+ лет постоянной пайки в моей банке визуально даже не стало меньше.

              Макетные платы без пайки

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

              Также есть такая вещь как провода для макетных плат - что-то вроде перемычек но длиннее: один, два. Постоянно использую при прототипировании, при помощи них можно соединить что угодно с чем угодно.

              Макетные платы для пайки

              Ссылки на размеры: 3x7 см., 6x4 см., 5x7 см., 6x6 см.и 7x9 см.
              Когда схема работает, надо делать ее более постоянную версию. Тут 2 выбора: либо разводить печатную плату, либо собрать на макетной плате. Почти все что я делаю - на макетках (такой уж  я ленивый)! Советую взять побольше таких. Самый ходовой размер - 5x7 см.

              Не берите макетки коричневого цвета!
              Они ломаются как будто сделаны из картона.

              Спирт для отмывания плат

              Все платы я отмываю. Если спаяна она активным флюсом, то это нужно для того чтобы он ее не разъел, если неактивным (например, канифолью) - то просто чтобы плата выглядела цивильно и на нее ничего не липло (кроме пыли может налипнуть какая-нибудь металлическая стружка, которая что-нибудь закоротит!).

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

              Инструменты

              Пинцет

              Малый изогнутый

              Ссылка на каталог в Chip Dip


              Малый изогнутый пинцет 1PK-104T (мой)

              То что я бы также порекомендовал взамен, если такой не находится:

              Пинцет DIYFIX

              Пинцет DONYAMY

              Большой


              Ссылка
              Рекомендации по выбору: стоит брать оффлайн. Не тот инструмент для которого работает прицип кота в мешке при покупке.

              Бокорезы (кусачки)


              Ссылка
              Рекомендации по выбору: вся серия бокорезов ИН имеет отличные режущие поверхности за счет победитовых насадок, но я беру только ИН-0011из-за такой простой вещи как пружина. Без нее очень неудобно работать - попробуйте!

              Третья рука

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

              Тонкогубцы (или как я их называю, длинногубцы :D )

              Ссылка 
              Также советую купить оффлайн. Мои тонкогубцы, также как и пинцет -  от Pro's Kit, модель 1PK-243. Качественные вещи делают ребята, уже долго пользуюсь и тем и тем.

              Очень важно чтобы удобно лежал в руке - этим могут похвастаться не все длинногубцы!

              Скальпель

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

              Отвертка шлицевая

              Ссылка
              Почему-то не крестовая, а именно шлицевая отвертка все время пригождается в электронике. Множество винтовых колодок открываются именно мелкой шлицевой отверткой.

              Острый нож (хобби-нож)


              Ссылка
              Полезное дополнение скальпелю для тонких работ. ОЧЕНЬ острый. В первое время можно обойтись без него.

              Надфиль

              Ссылка
              Такого мелкого хватает на все нужды. Не скупитесь и возьмите, чтобы Ваши устройства выглядели цивильно внутри и снаружи. Маст хев - вот такой плоский, но можно купить и набор напильников разных форм - это даже удобнее.

              Лупа

              Ссылка
              Как запаять микросхему с расстоянием между ногами 0.5мм. и не допустить короткого замыкания? Только при помощи хорошего наблюдения за процессом. При покупке станции с паяльным феном, стоит взять себе еще и лупу. Довольно неудобно держать ее в руках, поэтому советую сразу взять что-то вроде таких очков:

              Расходные материалы

              Термоусадочная трубка

              Ссылка
              Эстетически приятный и надежный способ изолировать соединения. Отрезаешь кусок, одеваешь на провод, нагреваешь. Самый ходовой диаметр - 2мм., но я обычно покупаю достаточное количество усадки от 1.5 до 4 мм. (скажем, 1.5 - 2метра, 2 - 4 метра, 2.5 - 3 метра и 4 - 2 метра), кроме того по метру остальных размеров больше 4мм. Диаметр 1мм. практически бесполезен.

              Изолента

              Ссылка? Зачем?
              Можно купить в любом магазине электронных и электрических товаров. Пригодится, конечно, но все же советую пользоваться термоусадкой. Хороший пример использования - изолирование соединения, которое может придется разъединить (во время создания прототипов например).

              Dead easy to make DIY hadware watchdog for your mining rig

              $
              0
              0

              Hi! Welcome to my regular DIY hardware post series. This time around, we're going to make a hardware watchdog timer for your mining rig (or any PC, actually).

              The focus of this device is its simplicity, as well as its constituent parts' cheapness and effortless sourcing. This build can be replicated even by those new to electronics and/or programming.

              We'll begin by gathering the parts:

              Parts

              Essentials

              All the part that you'll need. Provided you don't mind general ugliness.
              • Any Arduino. My choice was Uno as it's the most widespread one:


              • Reed relay. Picking this relatively obscure kind of relay was based on a specific rationale. This relay's coil consumes only about 9mA at 5V, so you can drive it directly from AVR's IO pin:


              • 0.100" (2.54 mm) male and female headers (both):

              Non-essentials (aka I don't want my device to fry because I poured some coffee on it) 

              Do you want your stuff to look decent? Then gather these parts.
              • Project enclosure. I'll be using a lunchbox (tada!) to accentuate the simplicity of gathering parts for the project. Can be found at the nearest grocery store.


              • Some kind of 2-pin panel mount connector. This build utilizes a simple barrel jack commonly used to supply DC power:

              • Tiny screws and standoffs to affix Arduino to your enclosure:

              Assembly

              1. Screw the Arduino to the bottom of the box. The standoffs will come in handy.

              2. Make the apertures both for your reset key connector and for Arduino's USB connector. Round hole can be made with the help of the conical drill bit:


              3. A square hole is a bit trickier. Personally, I heated up an awl and blazed the tip through the box to cut arbitrary shaped holes in it. Resulting edges have to be finished with a hobby knife and/or small file.

              4. Solder together a little circuit:

              5. One remaining piece is the cord that'll connect your watchdog timer to computer's motherboard.

              6. You're all set with the hardware! Just close the top of the box and plug it in!

              Software

              You'll find all required software (that is, Arduino sketch and Java program source code) along with detailed instructions in this Github repository. Java was chosen to ensure it can be run on both Windows and Linux - the two most widespread mining rig platforms.

              Java app being built with Maven - the same thing will be seen by any Linux user.

              Testing it all together


              Upload the sketch on Arduino, connect it to your computer and run the .jar file that you built. At this point, if everything works fine, you'll finally observe your hardware-software bundle of Arduino and Java working together:

              Here's how it works: the PC-side program tries to connect to every single serial port in your system within a period of 30 seconds (including the ports that appear during this process). To each port it'll send the handshake string "hello" and monitor the input, expecting to receive uppercase "HELLO" back. When the handshake is finished, it'll send ping strings once each five seconds.

              The watchdog program on Arduino scans the input for "ping" strings. If no such string has been received within 10 second period, the watchdog will forcibly restart your PC.

              Therefore, this scenario where you manually run it will be "one-off", i.e. once the PC has been restarted, the watchdog will be stuck in the pre-handshake state. To make it work all the time, add the Java program to the startup list of your operating system of choice.

              Now, the most important part is plugging your watchdog instead of the reset switch on your motherboard:

              That's when it'll be able to actually restart your PC.

              As a substitute for proper ending, have this video of my friend battle-testing my watchdog with one of his buggy GPUs that's been causing him way too many BSODs than you'll expect:

              TBD
              Viewing all 66 articles
              Browse latest View live