JavaRush /Java Blog /Random EN /We close contacts and receive a letter
Izhak
Level 22
Москва

We close contacts and receive a letter

Published in the Random EN group
Good afternoon, I would like to share my experience of creating an application that monitors the closure of pins 7 and 8 on a regular Chinese USB-COM adapter (RTS - CTS). And if such an event occurs, he sends me an email. Initially, the goal was to make a water flow sensor. What to do with the closure later is, by and large, unimportant, but I wanted to send the state to the post office. Since I am learning Java using JavaRush, the appropriate tool was chosen – IntelliJ Idea. Of course, mail is not SMS, but SMS requires working with a com port, and here we will learn a very good tool for this, and when I figure out the 3G modem, I can add a little information, although there is already a lot of it on the Internet. So, let's not focus on the hardware part, let's look at the connector itself DB9F . Pin 5 is ground, pin 7 is RTS - in our program there will always be 1 hanging on it (+ 9 V relative to pin 5), and pin 8 is the input - it pulled up by a 5 kilo-ohm resistor to 0 V. It must be said that when our program is not running, the voltage on pin 7 will be -9 V, this must be taken into account when you take a spill sensor, you can apply it to pin 8, but there are devices that burn from negative voltages. So, to check how our program will work, after launching it, we will close contact 7 to contact 8, our program will monitor such an event once a second and send a letter with the text “Puddle”, and then open it - and the program will send a letter with the text “Puddle”. There is no puddle." So, to install JDK and IntelliJ Idea and learn some java basics, you can use the first lessons of JavaRush.ru. We will start by creating a new project. Let me make a reservation right away that if you already have a project open, then when creating a new project you will be asked to open it in a new window - very convenient. (I once tried working with eclipse, where all projects open in one window). Next I give a lot of pictures without descriptions - and so everything is clear. We close the contacts and receive a letter - 1 We close the contacts and receive a letter - 2 We close the contacts and receive a letter - 2 We close the contacts and receive a letter - 4 We close the contacts and receive a letter - 3 We close the contacts and receive a letter - 6 We close the contacts and receive a letter - 4 We close the contacts and receive a letter - 8 We close the contacts and receive a letter - 5 Starting with the next picture, it’s very interesting - I’ve always seen this maven, but was afraid to do something with it, but then I tried it - and everything turned out to be very simple - if you need a library, you just enter its name, look for the latest version and download. Look. We download the library http://habrahabr.ru/post/133766/ jSSC And the javax:mail library - as I understand it, it was removed from the standard list of libraries, but it is easy to download in Maven. We close the contacts and receive a letter - 6 We close the contacts and receive a letter - 11 We close the contacts and receive a letter - 7 We close the contacts and receive a letter - 13 We close the contacts and receive a letter - 8 Click OK and the libraries are added. Voila :) We close the contacts and receive a letter - 9 Type the text comRun.java 1 package ru.example.comTest.Test1; 2 3 import jssc.*; 4 5 import java.io.UnsupportedEncodingException; 6 import java.util.Properties; 7 import javax.mail.*; 8 import javax.mail.internet.*; 9 10 /** 11 * Created by ipolma on 8/12/2014. 12 */ 13 14 public class comRun { 15 16 17 private static SerialPort serialPort; 18 19 public static void main(String[] args) { 20 21 22 String[] retPorts = SerialPortList.getPortNames(); 23 //for (String port: retPorts){System.out.println(port);} 24 25 serialPort = new SerialPort(retPorts[1]);//"COM4"); указываем второй порт 26 System.out.println(serialPort.getPortName()); 27 try { 28 //Открываем порт 29 if (serialPort.isOpened()) serialPort.closePort(); //Здесь бывает ситуация Busy, которую не обработаешь - только если ожидать 30 serialPort.openPort(); 31 //Выставляем параметры 32 serialPort.setParams(SerialPort.BAUDRATE_9600, 33 SerialPort.DATABITS_8, 34 SerialPort.STOPBITS_1, 35 SerialPort.PARITY_NONE); 36 //Включаем аппаратное управление потоком 37 serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | 38 SerialPort.FLOWCONTROL_RTSCTS_OUT); 39 40 int tempData0 = 0; 41 42 while(true){ 43 Thread.sleep(1000); 44 int[] data = serialPort.getLinesStatus();//readString(event.getEventValue()); 45 //7 и 8 контакты замыкаются - 1010 46 //разомкнуты - 0010 47 //7 и 6 контакты замыкаются - 0110 48 //data[0] - 12 В на 8 (CTS) 49 //data[1] - 12 В на 6 (DCE) 50 //serialPort.setDTR(status); //Меняется напряжение только на 4 контакте - но и это хорошо 51 //serialPort.setRTS(status); // На 7 не меняется- можно это использовать How выход +-7В. 52 53 if (data[0] == 1){ 54 tempData0 = 1; 55 sendEmail("Лужа"); 56 System.out.println("1"); 57 } 58 if (data[0] == 0 && tempData0 == 1){ 59 tempData0 =0; 60 System.out.println("0"); 61 sendEmail("Нет лужи"); 62 } 63 } 64 } 65 catch (SerialPortException ex) { 66 System.out.println(ex); 67 } 68 catch (InterruptedException ty){} 69 70 } 71 72 private static void sendEmail(String text){ 73 74 try { 75 // Создаем address отправителя и прлучателя 76 InternetAddress from = new InternetAddress("*****@yandex.ru", "From"); 77 InternetAddress to = new InternetAddress("****@****.ru", "To"); 78 // Далее создаем т.н. транспорт с определенными параметрами, который 79 // будет "заниматься" отправкой messages 80 Properties props = new Properties(); 81 // Тип протокола, address serverа и номер порта 82 props.put("mail.transport.protocol", "smtp"); 83 props.put("mail.smtp.host", "smtp.yandex.ru"); 84 props.put("mail.smtp.port", "25"); 85 Session session = Session.getDefaultInstance(props); 86 Transport transport = session.getTransport(); 87 // Теперь создаем сообщение 88 MimeMessage message = new MimeMessage(session); 89 message.setText(text, "utf-8"); 90 message.setFrom(from); 91 message.setRecipient(Message.RecipientType.TO, to); 92 message.setSubject("Тема", "utf-8"); 93 // При подключении указываем параметры для smtp serverа: логин и пароль 94 transport.connect("*****@yandex.ru", "**Password***"); 95 transport.sendMessage(message, new Address[]{to}); 96 transport.close(); 97 } catch (UnsupportedEncodingException ex) { 98 ex.printStackTrace(); 99 } catch (NoSuchProviderException ex) { 100 ex.printStackTrace(); 101 } catch (MessagingException ex) { 102 ex.printStackTrace(); 103 } 104 } 105 106 } 107 Set the existing addresses and passwords (by the way, it’s interesting that in the help on Yandex about smtp it is written about port 465, but on the Internet I found port 25 - and this turned out to be correct). Let's start execution. We close contacts 7 and 8, after three seconds we release 1 – the contacts are closed, the letter “Puddle” is sent, 0 – the contacts are open – the letter “No Puddle” is sent. This is what is in We close the contacts and receive a letter - 10 my mail We close the contacts and receive a letter - 17 We close the contacts and receive a letter - 11 We close the contacts and receive a letter - 19 Now I want to have an application. Here, while I was studying the material, I cried - is it really necessary to create a manifest file, register a class patch... a terrible thing. Skipy describes all this. I almost gave up, but in my kitchen desk drawers there were no punch cards long ago, and we had an idea, so I made a jar archive very simply - look. We close the contacts and receive a letter - 12 We close the contacts and receive a letter - 21 We close the contacts and receive a letter - 13 Check the Build on Make box - after the next compilation in idea, the result will be in the out folder. We close the contacts and receive a letter - 14 Everything is jar out, and is so independent that, in any case, within the machine it is copied and launched from anywhere. We close the contacts and receive a letter - 15 But if you just run it, then the letters will be sent, but there will be no console, and you can kill the process only by finding such an entry in the task manager. We close the contacts and receive a letter - 16 We transfer it to another folder, from there it also starts, and make a bat file. We close the contacts and receive a letter - 17 We close the contacts and receive a letter - 27 Launch the batch file We close the contacts and receive a letter - 18 We close the contacts and receive a letter - 29 . Here is the console, and using Ctrl + C - a request to exit. We close the contacts and receive a letter - 19 We close the contacts and receive a letter - 31 But if you run the jar twice, the second time will not work - the com port will be busy. Therefore, it is advisable to make a single application. We install Launch4j, launch it, select the output file - any name, it should be exe in the main window, then our jar, select the console type, minimum version 1.4.0 We We close the contacts and receive a letter - 20 We close the contacts and receive a letter - 33 We close the contacts and receive a letter - 21 We close the contacts and receive a letter - 35 indicate that we do not need many copies We close the contacts and receive a letter - 22 We close the contacts and receive a letter - 37 Click on the button with the gear We close the contacts and receive a letter - 23 We are asked where store temporary files, we answer We close the contacts and receive a letter - 24 We close the contacts and receive a letter - 40 Good Lak - everything is ready. Let's launch the executable. We close the contacts and receive a letter - 25 True, in the dispatcher it will still be executed under javaw We close the contacts and receive a letter - 26 Letters are coming We close the contacts and receive a letter - 43 Such things, I liked Java. PS. The best mechanical thing for monitoring leaks is http://www.vse-sam.ru/10249-mexanicheskaya-sistema-dlya-kontrolya-i-predotvrashheniya-protechki-vody.html PPS. Console output crashes the program after a certain number of lines, so if you suddenly repeat this algorithm, do not forget to disable console output.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION