├── my_components └── energy_meter_mercury230 │ ├── __init__.py │ ├── sensor.py │ ├── energy_meter_mercury230.h │ └── mercury230_proto.h ├── picturies ├── 0004.jpg ├── 001.jpg ├── 002.jpg ├── 003.jpg └── scheme.jpg ├── README.md ├── example └── energy-meter-mercury230.yaml └── LICENSE /my_components/energy_meter_mercury230/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /picturies/0004.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Brokly/ESPHome-Mercury230/HEAD/picturies/0004.jpg -------------------------------------------------------------------------------- /picturies/001.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Brokly/ESPHome-Mercury230/HEAD/picturies/001.jpg -------------------------------------------------------------------------------- /picturies/002.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Brokly/ESPHome-Mercury230/HEAD/picturies/002.jpg -------------------------------------------------------------------------------- /picturies/003.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Brokly/ESPHome-Mercury230/HEAD/picturies/003.jpg -------------------------------------------------------------------------------- /picturies/scheme.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Brokly/ESPHome-Mercury230/HEAD/picturies/scheme.jpg -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Home-Assistant-and-Mercury230 2 | Home Assistant, ESPhome и счетчик Меркурий 230 AR-01 3 | 4 | ИСПОЛЬЗУЯ ЭТОТ КОД, ПОЛЬЗОВАТЕЛЬ БЕРЕТ НА СЕБЯ ВСЮ ОТВЕТСТВЕННОСТЬ ЗА ПОСЛЕДСТВИЯ. 5 | Я СТРОГО НЕ РЕКОМЕНДУЮ ИСПОЛЬЗОВАТЬ ЭТО РЕШЕНИЕ В СИСТЕМАХ С НЕСКОЛЬКИМИ СЧЕТЧИКАМИ !!! 6 | 7 | - Очень советую использовать аппаратный UART. 8 | - Драйвер RS485 без ноги направления передачи, с защитными диодами и предохранителями (только так). 9 | - Счетчику требуется подача пятивольтового питания из вне. 10 | - Адрес счетчика не нужен, устройство найдет его само, если счетчик на шине RS485 один. 11 | 12 | Существуют необязательные параметры для установки подключения: 13 | 14 | Aдрес счетчика, если не указан будет попытка обнаружить его с использованием пароля, двузначная десятичная цифра 15 | use_address: xx 16 | 17 | Пароль УКАЗЫВАТЬ В КАВЫЧКАХ для подключения, в случае дефолтного можно не указывать, 6 любых символов 18 | password: "xxxxxxx" 19 | 20 | Тип пароля HEX или ASCII (true/false), если не знаете зачем это вам - просто не устанавливайте параметр 21 | pass_in_hex: 22 | 23 | Тип доступа пользователь или администратор (true/false) (АДМИНИСТРАТОР СТРОГО НЕ РЕКОМЕНДУЕТСЯ) 24 | admin: 25 | 26 | В случае подключения к сети счетчиков рекомендую установит update_interval: побольше, что бы управляющая компания вас не искала. 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /example/energy-meter-mercury230.yaml: -------------------------------------------------------------------------------- 1 | # Подключение ног ESP32 2 | # 3 | # Обязательный элемент 4 | # ModBus adapter https://esphome.io/_images/rs485.jpg 5 | # tx_pin: GPIO14 6 | # rx_pin: GPIO27 7 | # Дополнительные элементы, для работы не нужны 8 | # Led Red: gpio4 9 | # Led Blue: gpio16 10 | # Button: gpio32 11 | # Relay: gpio13 12 | 13 | # Имя устройства 14 | substitutions: 15 | devicename: mercury-230 16 | upper_devicename: Mercury-230 17 | location: В электрощите. # место установки 18 | 19 | external_components: 20 | - source: 21 | type: local 22 | path: my_components 23 | components: [ energy_meter_mercury230 ] 24 | refresh: 0s 25 | 26 | esphome: 27 | name: $devicename 28 | includes: 29 | - my_components/energy_meter_mercury230/energy_meter_mercury230.h 30 | - my_components/energy_meter_mercury230/mercury230_proto.h 31 | on_boot: 32 | priority: 600 33 | then: 34 | - script.execute: script_show_text 35 | 36 | esp32: 37 | board: esp32dev 38 | framework: 39 | type: arduino 40 | 41 | wifi: 42 | ssid: !secret wifi_ssid 43 | password: !secret wifi_pass 44 | manual_ip: 45 | static_ip: !secret ip_mercury-230 46 | gateway: !secret gateway 47 | subnet: !secret subnet 48 | dns1: !secret dns1 49 | dns2: !secret dns2 50 | ap: 51 | ssid: ${upper_devicename} Hotspot 52 | password: !secret ap_wifi_pass 53 | 54 | captive_portal: 55 | 56 | debug: 57 | 58 | logger: 59 | level: ERROR 60 | #level: DEBUG 61 | #baud_rate: 0 62 | 63 | api: 64 | # password: !secret api_pass 65 | 66 | ota: 67 | password: !secret ota_pass 68 | 69 | web_server: 70 | port: 80 71 | auth: 72 | username: !secret web_user 73 | password: !secret web_pass 74 | 75 | uart: 76 | id: uart_bus 77 | tx_pin: GPIO14 78 | rx_pin: GPIO27 79 | baud_rate: 9600 80 | data_bits: 8 81 | parity: NONE 82 | stop_bits: 1 83 | 84 | binary_sensor: 85 | #статус устройства 86 | - platform: status 87 | name: ${upper_devicename} HA Connected 88 | # кнопка 89 | - platform: gpio 90 | pin: 91 | number: GPIO32 92 | name: $upper_devicename Button 93 | internal: true 94 | on_click: 95 | # переключить реле при коротком нажатии 96 | - min_length: 10ms 97 | max_length: 1000ms 98 | then: 99 | - switch.toggle: relay_sw 100 | # restart esp , нужно зажать кнопку на 5000 секунд (ПОСЧИТАТЬ ДО 8) 101 | - min_length: 4000ms 102 | max_length: 6000ms 103 | then: 104 | - switch.toggle: restart_sw_id 105 | 106 | output: 107 | - platform: ledc 108 | id: red_led 109 | pin: 110 | number: GPIO4 111 | inverted: False 112 | 113 | light: 114 | - platform: monochromatic 115 | output: red_led 116 | id: relay_led 117 | default_transition_length: 1ms 118 | # для управления и индикации статуса 119 | # эта же нога используется для мигания при чтении ModBus 120 | - platform: status_led 121 | id: blue_led 122 | internal: true 123 | pin: GPIO16 124 | 125 | switch: 126 | #свитч рестарта устройства 127 | - platform: restart 128 | name: ${upper_devicename} Restart SW 129 | id: restart_sw_id 130 | # реле 131 | - platform: gpio 132 | id: relay 133 | pin: GPIO13 134 | #виртуальная кнопка, совмещает реле и диод 135 | - platform: template 136 | restore_state: true 137 | name: $upper_devicename Relay 138 | optimistic: true 139 | id: relay_sw 140 | internal: false 141 | turn_on_action: 142 | - switch.turn_on: relay 143 | - light.turn_on: relay_led 144 | turn_off_action: 145 | - switch.turn_off: relay 146 | - light.turn_off: relay_led 147 | #виртуальная кнопка, для скрытия длинного текста 148 | - platform: template 149 | name: $upper_devicename Hide Notes 150 | optimistic: true 151 | id: hide_notes 152 | entity_category: config 153 | icon: 'mdi:eye-off' 154 | turn_on_action: 155 | - script.execute: script_hide_text 156 | turn_off_action: 157 | - script.execute: script_show_text 158 | 159 | sensor: 160 | - platform: energy_meter_mercury230 161 | name: ${upper_devicename} 162 | # не забываем подключить uart 163 | uart_id: uart_bus 164 | 165 | # период цикла опроса счетчика 166 | update_interval: 30s 167 | # адрес счетчика (не обязательный), если не указан будет попытка обнаружить его с использованием пароля 168 | use_address: 00 169 | # пароль УКАЗЫВАТЬ В КАВЫЧКАХ для подключения (не обязательный), в случае дефолтного можно не указывать 170 | password: "______" 171 | # тип пароля HEX или ASCII 172 | #pass_in_hex: true 173 | 174 | # Напряжение по трем фазам 175 | voltage_a: 176 | id: VoltA 177 | name: ${upper_devicename} Volts A 178 | voltage_b: 179 | id: VoltB 180 | name: ${upper_devicename} Volts B 181 | voltage_c: 182 | id: VoltC 183 | name: ${upper_devicename} Volts C 184 | # Токи 185 | current_summ: 186 | id: Amps 187 | name: ${upper_devicename} Ampers Summ 188 | current_a: 189 | id: AmpA 190 | name: ${upper_devicename} Ampers A 191 | current_b: 192 | id: AmpB 193 | name: ${upper_devicename} Ampers B 194 | current_c: 195 | id: AmpC 196 | name: ${upper_devicename} Ampers C 197 | # Мощности 198 | power_summ: 199 | id: Watts 200 | name: ${upper_devicename} Watts Summ 201 | power_a: 202 | id: WattA 203 | name: ${upper_devicename} Watts A 204 | power_b: 205 | id: WattB 206 | name: ${upper_devicename} Watts B 207 | power_c: 208 | id: WattC 209 | name: ${upper_devicename} Watts C 210 | # Коэфициенты 211 | power_factor_a: 212 | id: RatioA 213 | name: ${upper_devicename} Ratio A 214 | power_factor_b: 215 | id: RatioB 216 | name: ${upper_devicename} Ratio B 217 | power_factor_c: 218 | id: RatioC 219 | name: ${upper_devicename} Ratio C 220 | # Фазовые углы 221 | phase_angle_a: 222 | id: AngleA 223 | name: ${upper_devicename} Angle A 224 | phase_angle_b: 225 | id: AngleB 226 | name: ${upper_devicename} Angle B 227 | phase_angle_c: 228 | id: AngleC 229 | name: ${upper_devicename} Angle C 230 | # Показания 231 | import_active_energy: 232 | id: ValueA 233 | name: ${upper_devicename} Value Active 234 | import_reactive_energy: 235 | id: ValueR 236 | name: ${upper_devicename} Value Reactive 237 | # Частота 238 | frequency: 239 | name: ${upper_devicename} Frequency 240 | id: Freq 241 | serial_number: 242 | name: ${upper_devicename} Serial Number 243 | id: sn_string 244 | connect_status: 245 | name: ${upper_devicename} Last Error 246 | id: error_string 247 | date_fabricate: 248 | name: ${upper_devicename} Date Fabricate 249 | id: fab_string 250 | # версия прошивки 251 | firmware_version: 252 | name: ${upper_devicename} Version 253 | id: ver_string 254 | # индикатор статуса связи 255 | active_led_pin: GPIO16 256 | # мощность WIFI сигнала 257 | - platform: wifi_signal 258 | name: ${upper_devicename} WiFi Signal 259 | update_interval: 30s 260 | unit_of_measurement: "dBa" 261 | state_class: measurement 262 | device_class: signal_strength 263 | accuracy_decimals: 0 264 | # время работы устройства после загрузки 265 | - platform: uptime 266 | name: ${upper_devicename} Uptime Sensor 267 | 268 | text_sensor: 269 | #версия прошивки 270 | - platform: version 271 | name: $upper_devicename ESPHome Version 272 | #текстовая форма uptime 273 | - platform: template 274 | name: ${upper_devicename} Uptime 275 | entity_category: diagnostic 276 | icon: 'mdi:timer' 277 | lambda: |- 278 | uint32_t dur=millis()/1000; 279 | char buffer[19]; 280 | if(dur>=86400) sprintf(buffer,"%ud %uh %02um %02us", dur/86400, dur%86400/3600, dur%3600/60, dur%60); 281 | else if(dur>=3600) sprintf(buffer,"%uh %02um %02us", dur/3600, dur%3600/60, dur%60); 282 | else sprintf(buffer,"%um %02us", dur/60, dur%60); 283 | return {buffer}; 284 | #локализация устройства, скрывается переключателем, для удобства работы в веб интерфейсе 285 | - platform: template 286 | name: ${upper_devicename} Location 287 | entity_category: diagnostic 288 | id: location 289 | icon: 'mdi:map-marker-radius' 290 | #железо устройства (на основе чего сделано), скрывается переключателем, для удобства работы в веб интерфейсе 291 | - platform: template 292 | name: ${upper_devicename} Hardware 293 | entity_category: diagnostic 294 | id: hardware 295 | icon: 'mdi:saw-blade' 296 | #точка подключения Wifi 297 | - platform: wifi_info 298 | ssid: 299 | name: ${upper_devicename} Connected SSID 300 | bssid: 301 | name: ${upper_devicename} Connected BSSID 302 | 303 | script: 304 | # процедура публикации большых текстовых кусков, сворачиваем для работы в веб морде 305 | - id: script_show_text 306 | then: 307 | - lambda: |- 308 | id(location).publish_state("${location}"); 309 | id(hardware).publish_state("ESP32 custom, ModBus adapter and other."); 310 | # процедура публикации большых текстовых кусков, сворачиваем для работы в веб морде 311 | - id: script_hide_text 312 | then: 313 | - lambda: |- 314 | char buffer[]="Turn 'Hide Notes'"; 315 | id(location).publish_state(buffer); 316 | id(hardware).publish_state(buffer); 317 | 318 | -------------------------------------------------------------------------------- /my_components/energy_meter_mercury230/sensor.py: -------------------------------------------------------------------------------- 1 | #import logging 2 | import esphome.config_validation as cv 3 | import esphome.codegen as cg 4 | from esphome import automation, pins 5 | from esphome.components import sensor, text_sensor, uart 6 | from esphome.automation import maybe_simple_id 7 | from esphome.const import ( 8 | CONF_ID, 9 | CONF_PIN, 10 | CONF_UART_ID, 11 | CONF_CURRENT, 12 | CONF_DATA, 13 | STATE_CLASS_MEASUREMENT, 14 | CONF_VALUE, 15 | CONF_MAX_VALUE, 16 | CONF_MIN_VALUE, 17 | CONF_STEP, 18 | CONF_UNIT_OF_MEASUREMENT, 19 | CONF_ACCURACY_DECIMALS, 20 | CONF_FREQUENCY, 21 | #DEVICE_CLASS_FREQUENCY, 22 | UNIT_HERTZ, 23 | CONF_VOLTAGE, 24 | DEVICE_CLASS_VOLTAGE, 25 | UNIT_VOLT, 26 | CONF_PHASE_ANGLE, 27 | UNIT_DEGREES, 28 | CONF_CURRENT, 29 | DEVICE_CLASS_CURRENT, 30 | UNIT_AMPERE, 31 | #ICON_CURRENT_AC, 32 | CONF_POWER, 33 | DEVICE_CLASS_POWER, 34 | UNIT_WATT, 35 | #ICON_POWER, 36 | UNIT_EMPTY, 37 | CONF_POWER_FACTOR, 38 | DEVICE_CLASS_POWER_FACTOR, 39 | CONF_IMPORT_ACTIVE_ENERGY, 40 | CONF_IMPORT_REACTIVE_ENERGY, 41 | UNIT_KILOWATT_HOURS, 42 | STATE_CLASS_TOTAL_INCREASING, 43 | DEVICE_CLASS_ENERGY, 44 | CONF_USE_ADDRESS, 45 | CONF_PASSWORD, 46 | CONF_UPDATE_INTERVAL, 47 | ) 48 | 49 | #_LOGGER = logging.getLogger(__name__) 50 | 51 | CODEOWNERS = ["@Brokly"] 52 | DEPENDENCIES = ["sensor", "text_sensor", "uart"] 53 | AUTO_LOAD = ["output"] 54 | 55 | CONF_ACTIVE_LED_PIN = "active_led_pin" 56 | CONF_FIRM_VERSION = "firmware_version" 57 | ICON_FIRM_VERSION = "mdi:select-inverse" 58 | CONF_SERIAL_NUMBER = "serial_number" 59 | ICON_SERIAL_NUMBER = "mdi:numeric" 60 | CONF_CONNECT_STATUS = "connect_status" 61 | ICON_CONNECT_STATUS = "mdi:lan-disconnect" 62 | CONF_DATA_FABRICATE = "date_fabricate" 63 | ICON_DATA_FABRICATE = "mdi:factory" 64 | ICON_PHASE_ANGLE = "mdi:alpha" 65 | #ICON_RATIO = "mdi:alpha-r-circle-outline" 66 | ICON_FREQUENCY = "mdi:sine-wave" 67 | CONF_ADMIN="admin" 68 | CONF_PASS_HEX="pass_in_hex" 69 | SUMM = "_summ" 70 | PhA = "_a" 71 | PhB = "_b" 72 | PhC = "_c" 73 | 74 | VALID_password_CHARACTERS = ( 75 | "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" 76 | ) 77 | 78 | Mercury230_ns = cg.esphome_ns.namespace("energy_meter_mercury230") 79 | Mercury230 = Mercury230_ns.class_("Mercury", sensor.Sensor, cg.Component) 80 | 81 | def output_info(config): 82 | #_LOGGER.info(config) 83 | return config 84 | 85 | def validate_password(value): 86 | value = cv.string_strict(value) 87 | if not value: 88 | return value 89 | if len(value) < 6: 90 | raise cv.Invalid("Password must be at 6 characters long") 91 | if len(value) > 6: 92 | raise cv.Invalid("Password must be at 6 characters long") 93 | for char in value: 94 | if char not in VALID_password_CHARACTERS: 95 | raise cv.Invalid( 96 | f"Password must only consist of upper/lowercase characters and numbers. The character '{char}' cannot be used" 97 | ) 98 | return value 99 | 100 | def validate_update_interval(value): 101 | value = cv.positive_time_period_milliseconds(value) 102 | if value < cv.time_period("5s"): 103 | raise cv.Invalid( 104 | "Update interval must be greater than or equal to 5 seconds if set." 105 | ) 106 | if value > cv.time_period("30min"): 107 | raise cv.Invalid( 108 | "The update interval must be greater than or equal to 30 minutes if set." 109 | ) 110 | return value 111 | 112 | #шаблон сенсора напряжений 113 | voltSensor=sensor.sensor_schema( 114 | state_class=STATE_CLASS_MEASUREMENT, 115 | device_class=DEVICE_CLASS_VOLTAGE, 116 | unit_of_measurement=UNIT_VOLT, 117 | #icon=???, 118 | accuracy_decimals=2, 119 | ) 120 | #шаблон сенсора мощности 121 | powerSensor=sensor.sensor_schema( 122 | state_class=STATE_CLASS_MEASUREMENT, 123 | device_class=DEVICE_CLASS_POWER, 124 | unit_of_measurement=UNIT_WATT, 125 | #icon=ICON_POWER, 126 | accuracy_decimals=2, 127 | ) 128 | #шаблон сенсора тока 129 | currentSensor=sensor.sensor_schema( 130 | state_class=STATE_CLASS_MEASUREMENT, 131 | device_class=DEVICE_CLASS_CURRENT, 132 | unit_of_measurement=UNIT_AMPERE, 133 | #icon=ICON_CURRENT_AC, 134 | accuracy_decimals=2, 135 | ) 136 | #шаблон сенсора углов 137 | angleSensor=sensor.sensor_schema( 138 | state_class=STATE_CLASS_MEASUREMENT, 139 | unit_of_measurement=UNIT_DEGREES, 140 | icon=ICON_PHASE_ANGLE, 141 | accuracy_decimals=2, 142 | ) 143 | #шаблон сенсора коефициентов 144 | ratioSensor=sensor.sensor_schema( 145 | state_class=STATE_CLASS_MEASUREMENT, 146 | device_class=DEVICE_CLASS_POWER_FACTOR, 147 | unit_of_measurement=UNIT_EMPTY, 148 | #icon=ICON_RATIO, 149 | accuracy_decimals=2, 150 | ) 151 | 152 | initParams = { 153 | cv.GenerateID(): cv.declare_id(Mercury230), 154 | # частота 155 | cv.Optional(CONF_FREQUENCY): sensor.sensor_schema( 156 | unit_of_measurement=UNIT_HERTZ, 157 | accuracy_decimals=1, 158 | #device_class=DEVICE_CLASS_FREQUENCY, 159 | state_class=STATE_CLASS_MEASUREMENT, 160 | icon=ICON_FREQUENCY, 161 | ), 162 | # активная энергия 163 | cv.Optional(CONF_IMPORT_ACTIVE_ENERGY): sensor.sensor_schema( 164 | unit_of_measurement=UNIT_KILOWATT_HOURS, 165 | accuracy_decimals=2, 166 | device_class=DEVICE_CLASS_ENERGY, 167 | state_class=STATE_CLASS_TOTAL_INCREASING, 168 | ), 169 | # реактивная энергия 170 | cv.Optional(CONF_IMPORT_REACTIVE_ENERGY): sensor.sensor_schema( 171 | unit_of_measurement=UNIT_KILOWATT_HOURS, 172 | accuracy_decimals=2, 173 | device_class=DEVICE_CLASS_ENERGY, 174 | state_class=STATE_CLASS_TOTAL_INCREASING, 175 | ), 176 | # версия прошивки устройства 177 | cv.Optional(CONF_FIRM_VERSION): text_sensor.text_sensor_schema( 178 | icon=ICON_FIRM_VERSION, 179 | ), 180 | # серийник устройства 181 | cv.Optional(CONF_SERIAL_NUMBER): text_sensor.text_sensor_schema( 182 | icon=ICON_SERIAL_NUMBER, 183 | ), 184 | # статус соединения 185 | cv.Optional(CONF_CONNECT_STATUS): text_sensor.text_sensor_schema( 186 | icon=ICON_CONNECT_STATUS, 187 | ), 188 | # дата изготовления 189 | cv.Optional(CONF_DATA_FABRICATE): text_sensor.text_sensor_schema( 190 | icon=ICON_DATA_FABRICATE, 191 | ), 192 | # нога светодиода индикации связи 193 | cv.Optional(CONF_ACTIVE_LED_PIN ): pins.gpio_output_pin_schema, 194 | # пароль для подключения 195 | cv.Optional(CONF_PASSWORD): validate_password, 196 | # пароль в HEX 197 | cv.Optional(CONF_PASS_HEX, default=False): cv.boolean, 198 | # тип пароля админский или нет 199 | cv.Optional(CONF_ADMIN, default=False): cv.boolean, 200 | # адрес счетчика 201 | cv.Optional(CONF_USE_ADDRESS): cv.int_range(min=1, max=240), 202 | # update interval 203 | cv.Optional(CONF_UPDATE_INTERVAL, default="30sec"): validate_update_interval, 204 | } 205 | 206 | # вольты 207 | initParams[cv.Optional(CONF_VOLTAGE+PhA)] = voltSensor; 208 | initParams[cv.Optional(CONF_VOLTAGE+PhB)] = voltSensor; 209 | initParams[cv.Optional(CONF_VOLTAGE+PhC)] = voltSensor; 210 | # мощности 211 | initParams[cv.Optional(CONF_POWER+PhA)] = powerSensor; 212 | initParams[cv.Optional(CONF_POWER+PhB)] = powerSensor; 213 | initParams[cv.Optional(CONF_POWER+PhC)] = powerSensor; 214 | initParams[cv.Optional(CONF_POWER+SUMM)] = powerSensor; 215 | # токи 216 | initParams[cv.Optional(CONF_CURRENT+PhA)] = currentSensor; 217 | initParams[cv.Optional(CONF_CURRENT+PhB)] = currentSensor; 218 | initParams[cv.Optional(CONF_CURRENT+PhC)] = currentSensor; 219 | initParams[cv.Optional(CONF_CURRENT+SUMM)] = currentSensor; 220 | # углы 221 | initParams[cv.Optional(CONF_PHASE_ANGLE+PhA)] = angleSensor; 222 | initParams[cv.Optional(CONF_PHASE_ANGLE+PhB)] = angleSensor; 223 | initParams[cv.Optional(CONF_PHASE_ANGLE+PhC)] = angleSensor; 224 | # коэфициенты 225 | initParams[cv.Optional(CONF_POWER_FACTOR+PhA)] = ratioSensor; 226 | initParams[cv.Optional(CONF_POWER_FACTOR+PhB)] = ratioSensor; 227 | initParams[cv.Optional(CONF_POWER_FACTOR+PhC)] = ratioSensor; 228 | 229 | CONFIG_SCHEMA = cv.All(sensor.sensor_schema(sensor.Sensor).extend(initParams).extend(uart.UART_DEVICE_SCHEMA).extend(cv.COMPONENT_SCHEMA), output_info) 230 | 231 | async def to_code(config): 232 | #_LOGGER.info("--------------") 233 | #_LOGGER.info(config) 234 | var = cg.new_Pvariable(config[CONF_ID]) 235 | await cg.register_component(var, config) 236 | #uart 237 | parent = await cg.get_variable(config[CONF_UART_ID]) 238 | cg.add(var.initUart(parent)) 239 | # прошивка 240 | if (CONF_FIRM_VERSION) in config: 241 | sens = await text_sensor.new_text_sensor(config[CONF_FIRM_VERSION]) 242 | cg.add(var.set_vers_string(sens)) 243 | # connect status 244 | if (CONF_CONNECT_STATUS) in config: 245 | sens = await text_sensor.new_text_sensor(config[CONF_CONNECT_STATUS]) 246 | cg.add(var.set_error_string(sens)) 247 | # дата изготовления 248 | if (CONF_DATA_FABRICATE) in config: 249 | sens = await text_sensor.new_text_sensor(config[CONF_DATA_FABRICATE]) 250 | cg.add(var.set_fab_date_string(sens)) 251 | # серийник устройства 252 | if (CONF_SERIAL_NUMBER) in config: 253 | sens = await text_sensor.new_text_sensor(config[CONF_SERIAL_NUMBER]) 254 | cg.add(var.set_sn_string(sens)) 255 | #нога светодиода сигнализации 256 | if (CONF_ACTIVE_LED_PIN ) in config: 257 | pin = await cg.gpio_pin_expression(config[CONF_ACTIVE_LED_PIN]) 258 | cg.add(var.set_active_pin(pin)) 259 | # частота 260 | if (CONF_FREQUENCY) in config: 261 | sens = await sensor.new_sensor(config[CONF_FREQUENCY]) 262 | cg.add(var.set_Freq(sens)) 263 | # активная энергия 264 | if (CONF_IMPORT_ACTIVE_ENERGY) in config: 265 | sens = await sensor.new_sensor(config[CONF_IMPORT_ACTIVE_ENERGY]) 266 | cg.add(var.set_ValueA(sens)) 267 | # реактивная энергия 268 | if (CONF_IMPORT_REACTIVE_ENERGY) in config: 269 | sens = await sensor.new_sensor(config[CONF_IMPORT_REACTIVE_ENERGY]) 270 | cg.add(var.set_ValueR(sens)) 271 | # вольты 272 | if (CONF_VOLTAGE+PhA) in config: 273 | sens = await sensor.new_sensor(config[CONF_VOLTAGE+PhA]) 274 | cg.add(var.set_VoltA(sens)) 275 | if (CONF_VOLTAGE+PhB) in config: 276 | sens = await sensor.new_sensor(config[CONF_VOLTAGE+PhB]) 277 | cg.add(var.set_VoltB(sens)) 278 | if (CONF_VOLTAGE+PhC) in config: 279 | sens = await sensor.new_sensor(config[CONF_VOLTAGE+PhC]) 280 | cg.add(var.set_VoltC(sens)) 281 | # мощности 282 | if (CONF_POWER+PhA) in config: 283 | sens = await sensor.new_sensor(config[CONF_POWER+PhA]) 284 | cg.add(var.set_WattA(sens)) 285 | if (CONF_POWER+PhB) in config: 286 | sens = await sensor.new_sensor(config[CONF_POWER+PhB]) 287 | cg.add(var.set_WattB(sens)) 288 | if (CONF_POWER+PhC) in config: 289 | sens = await sensor.new_sensor(config[CONF_POWER+PhC]) 290 | cg.add(var.set_WattC(sens)) 291 | if (CONF_POWER+SUMM) in config: 292 | sens = await sensor.new_sensor(config[CONF_POWER+SUMM]) 293 | cg.add(var.set_Watts(sens)) 294 | # токи 295 | if (CONF_CURRENT+PhA) in config: 296 | sens = await sensor.new_sensor(config[CONF_CURRENT+PhA]) 297 | cg.add(var.set_AmpA(sens)) 298 | if (CONF_CURRENT+PhB) in config: 299 | sens = await sensor.new_sensor(config[CONF_CURRENT+PhB]) 300 | cg.add(var.set_AmpB(sens)) 301 | if (CONF_CURRENT+PhC) in config: 302 | sens = await sensor.new_sensor(config[CONF_CURRENT+PhC]) 303 | cg.add(var.set_AmpC(sens)) 304 | if (CONF_CURRENT+SUMM) in config: 305 | sens = await sensor.new_sensor(config[CONF_CURRENT+SUMM]) 306 | cg.add(var.set_Amps(sens)) 307 | # углы 308 | if (CONF_PHASE_ANGLE+PhA) in config: 309 | sens = await sensor.new_sensor(config[CONF_PHASE_ANGLE+PhA]) 310 | cg.add(var.set_AngleA(sens)) 311 | if (CONF_PHASE_ANGLE+PhB) in config: 312 | sens = await sensor.new_sensor(config[CONF_PHASE_ANGLE+PhB]) 313 | cg.add(var.set_AngleB(sens)) 314 | if (CONF_PHASE_ANGLE+PhC) in config: 315 | sens = await sensor.new_sensor(config[CONF_PHASE_ANGLE+PhC]) 316 | cg.add(var.set_AngleC(sens)) 317 | # коэфициенты 318 | if (CONF_POWER_FACTOR+PhA) in config: 319 | sens = await sensor.new_sensor(config[CONF_POWER_FACTOR+PhA]) 320 | cg.add(var.set_RatioA(sens)) 321 | if (CONF_POWER_FACTOR+PhB) in config: 322 | sens = await sensor.new_sensor(config[CONF_POWER_FACTOR+PhB]) 323 | cg.add(var.set_RatioB(sens)) 324 | if (CONF_POWER_FACTOR+PhC) in config: 325 | sens = await sensor.new_sensor(config[CONF_POWER_FACTOR+PhC]) 326 | cg.add(var.set_RatioC(sens)) 327 | 328 | # пароли 329 | if (CONF_PASSWORD ) in config: 330 | cg.add(var.set_pass(config[CONF_PASSWORD])) 331 | # уровень доступа 332 | if (CONF_ADMIN ) in config: 333 | cg.add(var.set_admin(config[CONF_ADMIN])) 334 | # пароль в HEX 335 | if (CONF_PASS_HEX ) in config: 336 | cg.add(var.set_hex_pass(config[CONF_PASS_HEX])) 337 | # адрес счетчика 338 | if (CONF_USE_ADDRESS) in config: 339 | cg.add(var.set_useraddr(config[CONF_USE_ADDRESS])) 340 | # update intrerval 341 | if (CONF_UPDATE_INTERVAL) in config: 342 | cg.add(var.set_update_interval(config[CONF_UPDATE_INTERVAL])) 343 | 344 | -------------------------------------------------------------------------------- /my_components/energy_meter_mercury230/energy_meter_mercury230.h: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #ifndef ENERGY_METER_MERCURY230_H 5 | #define ENERGY_METER_MERCURY230_H 6 | 7 | //#include 8 | #include "esphome.h" 9 | #include 10 | #include "esphome/core/log.h" 11 | #include "esphome/core/helpers.h" 12 | #include "esphome/core/component.h" 13 | #include "esphome/components/sensor/sensor.h" 14 | #include "esphome/components/text_sensor/text_sensor.h" 15 | #include "esphome/components/uart/uart.h" 16 | 17 | namespace esphome { 18 | namespace energy_meter_mercury230 { 19 | 20 | using namespace esphome; 21 | using sensor::Sensor; 22 | using text_sensor::TextSensor; 23 | using uart::UARTDevice; 24 | using uart::UARTComponent; 25 | 26 | class Mercury : public Sensor, public PollingComponent { 27 | 28 | //коды ошибок 29 | enum _replyReason:uint8_t { REP_OK=0, //Все нормально 30 | ERROR_COMMAND=1, //Недопустимая команда или параметр 31 | ERROR_HARDWARE=2,//Внутренняя ошибка счетчика 32 | ERROR_ACCESS_LEVEL=3,//Недостаточен уровень доступа для запроса 33 | ERROR_CORE_TIME=4, //Внутренние часы счетчика уже корректировались в течение текущих суток 34 | ERROR_CONNECTION=5, //Не открыт канал связи 35 | ERROR_TIMEOUT=6, //Ошибка ответа, ошибка КС 36 | BUFFER_OVERFLOW=7 // переполнение буфера 37 | }; 38 | 39 | //типы функций обратного вызова 40 | typedef void (*callBack1_t)(float); 41 | typedef void (*callBackStr_t)(char*); 42 | typedef void (*callBack2_t)(float,float); 43 | typedef void (*callBack3_t)(float,float,float); 44 | typedef void (*callBack4_t)(float,float,float,float); 45 | typedef void (*debug_t)(uint8_t, uint8_t*); 46 | 47 | // типы пакетов по теме 48 | enum _packetType:uint8_t { _OK=0, // пакет проверки связи, используется только при тесте или пинге 49 | CONNECT=1, // установка конекта 50 | CLOSE=2, // закрытие конекта 51 | WRITE=3, // запись 52 | READ=4, // чтение параметров 53 | LIST=5, // чтение журналов 54 | READ_PARAMS=8 // чтение доп параметров 55 | }; 56 | 57 | // тип пакета в буфере отправки 58 | enum _currentSend:uint8_t { NONE=0, //в буфере нет пакета 59 | GET_TEST, 60 | GET_ACCESS, 61 | WRITE_TIME, 62 | CORE_TIME, 63 | GET_TIME, 64 | GET_POWER, 65 | GET_VOLTAGE, 66 | GET_CURRENT, 67 | GET_KOEF_POWER, 68 | GET_FREQ, 69 | GET_ANGLE_PH, 70 | GET_DISTORTION, 71 | GET_TEMP, 72 | GET_LINEAR_VOLTAGE, 73 | GET_VERS, 74 | GET_SER_NUM, 75 | GET_TIME_CODE, 76 | GET_CRC, 77 | GET_VALUE, 78 | GET_ADDR 79 | }; 80 | 81 | // тип запроса чтения параметров 82 | enum _reqType:uint8_t { PARAM_SER_NUM = 0 , // серийный номер и дату 83 | PARAM_VERS = 3, // версия 84 | PARAM_UNO = 0x11, // читаем один конкретный параметр, НЕ БУДУ ИСПОЛЬЗОВАТЬ 85 | PARAM_ALL_FULL = 0x14, // ответ по всем фазам, списком, без сокращения незначащих битов 86 | PARAM_ALL = 0x16, // ответ по всем фазам, списком, в сокращенном формате, при запросе указывать фазу 1(!!!) 87 | PARAM_CRC = 0x26 // читаем CRC прибора 88 | }; 89 | 90 | //================== ИСХОДЯЩИЕ ПАКЕТЫ ======================== 91 | 92 | // общий буфер отправки 93 | struct _sBuff{ 94 | uint8_t addr; // адрес счетчика 95 | _packetType packType; // тип пакета 96 | uint8_t data[30]; // тело буфера 97 | }; 98 | 99 | private: 100 | // буфера работы с пакетами 101 | uint8_t inPacket[32]; 102 | uint8_t sizeInPacket=0; 103 | uint8_t outPacket[32]; 104 | uint8_t sizeOutPacket=0; 105 | std::string pass=""; // буфер пароля для подключения к счетчику 106 | bool act_pass=false; // пароль указан пользователем 107 | bool pas_in_hex=false; // ПАРОЛЬ в виде HEX 108 | bool admin=false; // тип доступа 109 | uint8_t addr=0; // адрес счетчика 110 | 111 | #include "mercury230_proto.h" 112 | 113 | // указатель на UART, по которому общаемся с кондиционером 114 | UARTComponent *my_serial{nullptr}; 115 | Sensor *VoltA {nullptr}; 116 | Sensor *VoltB {nullptr}; 117 | Sensor *VoltC {nullptr}; 118 | Sensor *Amps {nullptr}; 119 | Sensor *AmpA {nullptr}; 120 | Sensor *AmpB {nullptr}; 121 | Sensor *AmpC {nullptr}; 122 | Sensor *Watts {nullptr}; 123 | Sensor *WattA {nullptr}; 124 | Sensor *WattB {nullptr}; 125 | Sensor *WattC {nullptr}; 126 | Sensor *RatioA {nullptr}; 127 | Sensor *RatioB {nullptr}; 128 | Sensor *RatioC {nullptr}; 129 | Sensor *AngleA {nullptr}; 130 | Sensor *AngleB {nullptr}; 131 | Sensor *AngleC {nullptr}; 132 | Sensor *Freq {nullptr}; 133 | Sensor *ValueA {nullptr}; 134 | Sensor *ValueR {nullptr}; 135 | TextSensor *vers_string {nullptr}; 136 | TextSensor *error_string {nullptr}; 137 | TextSensor *sn_string {nullptr}; 138 | TextSensor *fab_date_string {nullptr}; 139 | GPIOPin* led_active_pin{nullptr}; 140 | //флаги обработок 141 | bool cbPower=false; 142 | bool cbVolt=false; 143 | bool cbCurrent=false; 144 | bool cbKoef=false; 145 | bool cbAngles=false; 146 | bool cbFreq=false; 147 | bool cbValues=false; 148 | 149 | // калбэки для отладки 150 | bool debugIn=false; 151 | bool debugOut=false; 152 | 153 | const uint32_t minUpdatePeriod = 5000; 154 | const char *const TAG = "Mercury"; 155 | 156 | // вывод отладочной информации в лог 157 | // 158 | // dbgLevel - уровень сообщения, определен в ESPHome. За счет его использования можно из ESPHome управлять полнотой сведений в логе. 159 | // msg - сообщение, выводимое в лог 160 | // line - строка, на которой произошел вызов (удобно при отладке) 161 | // 162 | // Своровал, спасибо GrKoR :) 163 | void _debugMsg(const std::string &msg, uint8_t dbgLevel = ESPHOME_LOG_LEVEL_DEBUG, unsigned int line = 0, ... ){ 164 | if (dbgLevel < ESPHOME_LOG_LEVEL_NONE) dbgLevel = ESPHOME_LOG_LEVEL_NONE; 165 | if (dbgLevel > ESPHOME_LOG_LEVEL_VERY_VERBOSE) dbgLevel = ESPHOME_LOG_LEVEL_VERY_VERBOSE; 166 | if (line == 0) line = __LINE__; // если строка не передана, берем текущую строку 167 | va_list vl; 168 | va_start(vl, line); 169 | esp_log_vprintf_(dbgLevel, TAG, line, msg.c_str(), vl); 170 | va_end(vl); 171 | } 172 | 173 | // выводим данные пакета в лог для отладки 174 | // 175 | // dbgLevel - уровень сообщения, определен в ESPHome. За счет его использования можно из ESPHome управлять полнотой сведений в логе. 176 | // packet - указатель на пакет для вывода; 177 | // если указатель на crc равен nullptr или первый байт в буфере не AC_PACKET_START_BYTE, то считаем, что передан битый пакет 178 | // или не пакет вовсе. Для такого выводим только массив байт. 179 | // Для нормального пакета данные выводятся с форматированием. 180 | // line - строка, на которой произошел вызов (удобно при отладке) 181 | // 182 | void _debugPrintPacket(uint8_t* data, uint8_t size, bool in, uint8_t dbgLevel = ESPHOME_LOG_LEVEL_DEBUG, unsigned int line = 0){ 183 | std::string st = ""; 184 | char textBuf[11]; 185 | // заполняем время получения пакета 186 | memset(textBuf, 0, 11); 187 | sprintf(textBuf, "%010u", millis()); 188 | st = st + textBuf + ": "; 189 | // формируем преамбулы 190 | if (in) { 191 | st += "[<=] "; // признак входящего пакета 192 | } else { 193 | st += "[=>] "; // признак исходящего пакета 194 | } 195 | for (uint8_t i=0; iget_rx_buffer_size()); 220 | //ESP_LOGCONFIG(TAG, " Baud Rate: %u baud", my_serial->get_baud_rate()); 221 | //ESP_LOGCONFIG(TAG, " Data Bits: %u", my_serial->get_data_bits()); 222 | //ESP_LOGCONFIG(TAG, " Parity: %s", LOG_STR_ARG(parity_to_str(my_serial->get_parity()))); 223 | //ESP_LOGCONFIG(TAG, " Stop bits: %u", my_serial->get_stop_bits()); 224 | ESP_LOGCONFIG(TAG, "Update interval: %u sec", (this->update_interval_/1000)); 225 | LOG_SENSOR("", "Voltage phase A ", this->VoltA); 226 | LOG_SENSOR("", "Voltage phase B ", this->VoltB); 227 | LOG_SENSOR("", "Voltage phase C ", this->VoltC); 228 | LOG_SENSOR("", "Amperage Summ ", this->Amps); 229 | LOG_SENSOR("", "Amperage phase A ", this->AmpA); 230 | LOG_SENSOR("", "Amperage phase B ", this->AmpB); 231 | LOG_SENSOR("", "Amperage phase C ", this->AmpC); 232 | LOG_SENSOR("", "Watts All ", this->Watts); 233 | LOG_SENSOR("", "Watts phase A ", this->WattA); 234 | LOG_SENSOR("", "Watts phase B ", this->WattB); 235 | LOG_SENSOR("", "Watts phase C ", this->WattC); 236 | LOG_SENSOR("", "Ratio phase A ", this->RatioA); 237 | LOG_SENSOR("", "Ratio phase B ", this->RatioB); 238 | LOG_SENSOR("", "Ratio phase C ", this->RatioC); 239 | LOG_SENSOR("", "Phase shift AB ", this->AngleA); 240 | LOG_SENSOR("", "Phase shift BC ", this->AngleB); 241 | LOG_SENSOR("", "Phase shift CA ", this->AngleC); 242 | LOG_SENSOR("", "Frequency", this->Freq); 243 | LOG_SENSOR("", "Values Active+ ", this->ValueA); 244 | LOG_SENSOR("", "Values Reactive+ ", this->ValueR); 245 | LOG_TEXT_SENSOR("", "Date of Мanufacture ", this->fab_date_string); 246 | LOG_TEXT_SENSOR("", "Serial Number ", this->sn_string); 247 | LOG_TEXT_SENSOR("", "Version ", this->vers_string); 248 | LOG_TEXT_SENSOR("", "Last Error ", this->error_string); 249 | LOG_PIN("Active pin ", this->led_active_pin); 250 | // параметры предустановленные пользователем 251 | if(addr){ 252 | ESP_LOGCONFIG(TAG,"Device address: %02u", addr); 253 | } 254 | uint8_t buff[6]={0}; 255 | if(act_pass){ 256 | if(pas_in_hex){ 257 | if(!getPass(buff)){ 258 | ESP_LOGE(TAG, "Password wrong"); 259 | act_pass=false; 260 | } 261 | } 262 | } 263 | if(act_pass){ 264 | if(pas_in_hex){ 265 | ESP_LOGCONFIG(TAG, "Password in HEX"); 266 | } else { 267 | ESP_LOGCONFIG(TAG, "Password in ASCII"); 268 | } 269 | ESP_LOGCONFIG("", "Password for send: %X,%X,%X,%X,%X,%X",buff[0],buff[1],buff[2],buff[3],buff[4],buff[5]); 270 | } 271 | if(admin){ 272 | ESP_LOGCONFIG("", "Access level: ADMIN (highly not recommended)"); 273 | } 274 | } 275 | 276 | // подключение последовательного интерфейса 277 | void initUart(UARTComponent *parent = nullptr){ my_serial=parent;} 278 | // подключение сенсоров и прочего 279 | void set_VoltA(sensor::Sensor *sens) {this->VoltA=sens;} 280 | void set_VoltB(sensor::Sensor *sens) {this->VoltB=sens;} 281 | void set_VoltC(sensor::Sensor *sens) {this->VoltC=sens;} 282 | void set_Amps(sensor::Sensor *sens) {this->Amps=sens;} 283 | void set_AmpA(sensor::Sensor *sens) {this->AmpA=sens;} 284 | void set_AmpB(sensor::Sensor *sens) {this->AmpB=sens;} 285 | void set_AmpC(sensor::Sensor *sens) {this->AmpC=sens;} 286 | void set_Watts(sensor::Sensor *sens) {this->Watts=sens;} 287 | void set_WattA(sensor::Sensor *sens) {this->WattA=sens;} 288 | void set_WattB(sensor::Sensor *sens) {this->WattB=sens;} 289 | void set_WattC(sensor::Sensor *sens) {this->WattC=sens;} 290 | void set_RatioA(sensor::Sensor *sens) {this->RatioA=sens;} 291 | void set_RatioB(sensor::Sensor *sens) {this->RatioB=sens;} 292 | void set_RatioC(sensor::Sensor *sens) {this->RatioC=sens;} 293 | void set_AngleA(sensor::Sensor *sens) {this->AngleA=sens;} 294 | void set_AngleB(sensor::Sensor *sens) {this->AngleB=sens;} 295 | void set_AngleC(sensor::Sensor *sens) {this->AngleC=sens;} 296 | void set_Freq(sensor::Sensor *sens) {this->Freq=sens;} 297 | void set_ValueA(sensor::Sensor *sens) {this->ValueA=sens;} 298 | void set_ValueR(sensor::Sensor *sens) {this->ValueR=sens;} 299 | // версия 300 | void set_vers_string(text_sensor::TextSensor *sens) { this->vers_string = sens;} 301 | // ошибка 302 | void set_error_string(text_sensor::TextSensor *sens) { this->error_string = sens;} 303 | // серийный номер 304 | void set_sn_string(text_sensor::TextSensor *sens) { this->sn_string = sens;} 305 | // дата изготовления 306 | void set_fab_date_string(text_sensor::TextSensor *sens) { this->fab_date_string = sens;} 307 | // нога индикации работы 308 | void set_active_pin(GPIOPin *pin){ this->led_active_pin=pin; this->led_active_pin->setup();} 309 | // пароль для подключения к счетчику 310 | void set_pass(const std::string &pass){this->pass=pass; act_pass=true;} 311 | // вид пароля (HEX ли ASCII) 312 | void set_hex_pass(bool pas_in_hex){this->pas_in_hex=pas_in_hex;} 313 | // тип доступа 314 | void set_admin(bool admin){this->admin=admin;} 315 | // пользовательский адрес счетчика 316 | void set_useraddr(uint8_t addr){this->addr=addr;} 317 | // период опроса 318 | void set_update_interval(uint32_t update_interval){this->update_interval_=update_interval;} 319 | 320 | void setup() override { 321 | 322 | if (this->update_interval_<5000){ 323 | this->update_interval_=30000; 324 | } 325 | 326 | // СВЕТОДИОД, синий встроенный, показывает активность на шине обмена 327 | if(this->led_active_pin!=nullptr){ 328 | this->led_active_pin->pin_mode(gpio::FLAG_OUTPUT); 329 | this->led_active_pin->digital_write(false); // опустить ногу :) 330 | } 331 | 332 | // хочу мощный сигнал 333 | //esp_wifi_set_max_tx_power(80); 334 | 335 | // установим функции обратного вызова, параметров которые хотим получать 336 | cbPower=(this->Watts!=nullptr || this->WattA!=nullptr || this->WattB!=nullptr || WattC!=nullptr); 337 | cbVolt=(this->VoltA!=nullptr || this->VoltB!=nullptr || this->VoltC!=nullptr); 338 | cbCurrent=(this->Amps!=nullptr || this->AmpA!=nullptr || this->AmpB!=nullptr || AmpC!=nullptr); 339 | cbKoef=(this->RatioA!=nullptr || this->RatioB!=nullptr || this->RatioC!=nullptr); 340 | cbAngles=(this->AngleA!=nullptr || this->AngleB!=nullptr || this->AngleC!=nullptr); 341 | cbFreq=(this->Freq!=nullptr); 342 | cbValues=(this->ValueA!=nullptr || this->ValueR!=nullptr); 343 | // включение отладки (TODO: увязать с флагом отладки) 344 | debugIn=true; // будем печатать входящие 345 | debugOut=true; // и исходящие пакеты 346 | // инициализация, адрес устройства 0 - поиск адреса 347 | setupMerc(minUpdatePeriod); // 348 | } 349 | 350 | void loop() override { 351 | 352 | // если подключен uart 353 | if(this->my_serial!=nullptr){ 354 | // если в буфере приема UART есть данные, значит счетчик что то прислал 355 | if(this->my_serial->available()){ 356 | uint8_t data; 357 | this->my_serial->read_byte(&data); // получили байт от счетчика 358 | getFromMerc(data); // передать байт в работу 359 | if(this->led_active_pin!=nullptr){this->led_active_pin->digital_write(false);} 360 | } 361 | 362 | uint8_t data=availableMerc(); // количество байт для отправки 363 | // если в буфере отправки есть данные - отправить счетчику 364 | // счетчик очень капризен к даймаутам, отправлять нужно непрерывным потоком !!! 365 | if(data){ 366 | uint8_t* buff=getBuffForMerc(); 367 | this->my_serial->write_array(buff,data); 368 | if(this->led_active_pin!=nullptr){this->led_active_pin->digital_write(true);} 369 | //_debugPrintPacket(buff, data, false); 370 | //return; // тут нельзя долго сидеть :( 371 | } 372 | } 373 | 374 | // если нужно печатаем в лог исходящий пакет 375 | if(sizeOutPacket){ 376 | this->_debugPrintPacket(outPacket, sizeOutPacket, false); 377 | sizeOutPacket=0; 378 | } 379 | 380 | // если нужно печатаем в лог входящий пакет 381 | if(sizeInPacket){ 382 | this->_debugPrintPacket(inPacket, sizeInPacket, true); 383 | sizeInPacket=0; 384 | } 385 | 386 | } 387 | 388 | void update() override { 389 | 390 | // автокоррекция периода опроса 391 | static uint32_t upd_int = this->update_interval_; 392 | static uint32_t upd_period = upd_int-1; 393 | if(upd_int != upd_period){ 394 | upd_period = upd_int; 395 | if(upd_period < minUpdatePeriod){ 396 | upd_period = minUpdatePeriod; 397 | } 398 | this->setUpdatePeriod(upd_period); 399 | this->_debugMsg("Core scan period %u", ESPHOME_LOG_LEVEL_ERROR, __LINE__, upd_period); 400 | upd_period = upd_int; 401 | } 402 | 403 | // контролируем ошибки связи и момент их возникновения 404 | static _replyReason oldError = ERROR_CORE_TIME; 405 | if(oldError != getLastError()){ //если изменился статус ошибки 406 | oldError = getLastError(); // запомним новый статус 407 | if(this->error_string!=nullptr){ // публикация ошибок 408 | this->error_string->publish_state(getStrError(oldError)); 409 | } 410 | if(oldError==REP_OK){ 411 | _debugMsg("No errors !", ESPHOME_LOG_LEVEL_INFO, __LINE__); 412 | } else { 413 | _debugMsg("Error: %s", ESPHOME_LOG_LEVEL_ERROR, __LINE__, getStrError(oldError)); 414 | } 415 | } 416 | 417 | } 418 | 419 | }; 420 | 421 | } // namespace energy_meter_mercury230 422 | } // namespace esphome 423 | 424 | #endif //ENERGY_METER_MERCURY230_H 425 | -------------------------------------------------------------------------------- /my_components/energy_meter_mercury230/mercury230_proto.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #ifndef MERCURY230_PROTO_H 3 | #define MERCURY230_PROTO_H 4 | 5 | #define PASS_1 "\1\1\1\1\1\1" 6 | #define PASS_2 "\2\2\2\2\2\2" 7 | 8 | #define PACKET_MIN_DELAY 500 9 | #define ABORT_RECIVE_TIME 50 10 | #define MIN_SCAN_PERIOD 2000 11 | 12 | 13 | //============================ ПЕРЕМЕННЫЕ ======================= 14 | uint8_t readBuff[32] = {0}; // буфер входящих данных 15 | uint8_t fromReadArrow = 0; // указатель точки заполнения буфера приема 16 | uint8_t sendBuff[32] = {0}; // буфер отправки 17 | _sBuff* sBuff = (_sBuff*)sendBuff; // фантом буфера отправки 18 | uint8_t forSendSize = 0; // количество данных в буфере отправки 19 | uint8_t forSendArrow = 0; // указатель на очередной байт в буфере для отправки 20 | _currentSend forSenfType = NONE; // тип пакета в буфере отправки, что ждем от пакета приема 21 | uint32_t scanPeriod = 0xFFFFFFFF; // период сканирования 22 | uint32_t timeReadByte=0; //тут время последнего получения байта 23 | uint32_t timeSendByte=0; //время последней отправки байта 24 | uint16_t mainCRC=0; // CRC прибора 25 | bool procError=false; // если во время цикла опроса возикнет ошибка 26 | bool waiteReply = false; // флаг ожидания ответа, поднимается при отправке, снимается при получении 27 | _replyReason lastError=REP_OK; // последний статус ответа 28 | uint32_t scanTimer=millis(); // таймер периодов связи 29 | 30 | //==================== ОБМЕН ДАННЫМИ =================================== 31 | // таблица быстрого рассчета КС 32 | uint16_t crcTable[256] = { 33 | 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 34 | 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, 35 | 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 36 | 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, 37 | 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, 38 | 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41, 39 | 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641, 40 | 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040, 41 | 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240, 42 | 0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, 43 | 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 44 | 0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, 45 | 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 46 | 0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40, 47 | 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640, 48 | 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041, 49 | 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240, 50 | 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441, 51 | 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, 52 | 0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, 53 | 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 54 | 0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, 55 | 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640, 56 | 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041, 57 | 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241, 58 | 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440, 59 | 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40, 60 | 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, 61 | 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 62 | 0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, 63 | 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 64 | 0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040 65 | }; 66 | 67 | // дебильный формат меркурия, программист дятел. 68 | uint32_t dm32_3(uint8_t* d){ 69 | return (((((uint32_t)(d[0]&0x3f))<<8)+d[2])<<8)+d[1]; 70 | } 71 | uint32_t dm32_4(uint8_t* d){ 72 | return (((((((uint32_t)d[1])<<8)+d[0])<<8)+d[3])<<8)+d[2]; 73 | } 74 | 75 | // для подсчета CS на лету 76 | uint16_t stepCrc16mb(uint8_t in, bool start=false){ 77 | static uint16_t crc=0xFFFF; 78 | if(start){ // первое обращение 79 | crc=0xFFFF; 80 | } 81 | crc = ((crc >> 8) ^ crcTable[(crc ^ in) & 0xFF]); 82 | return crc; 83 | } 84 | // подсчет контрольной суммы сразу в буфере 85 | uint8_t crc16mb(uint8_t *s, uint8_t count) { 86 | uint16_t* crc=(uint16_t*)(&(s[count-2])); 87 | *crc=0xFFFF; 88 | for(int i = 0; i < count-2; i++) { 89 | *crc = ((*crc >> 8) ^ crcTable[(*crc ^ s[i]) & 0xFF]); 90 | } 91 | if(debugOut){ // показываем буфер для отладки 92 | inDataReady(count, sendBuff); 93 | } 94 | return count; 95 | } 96 | 97 | // получить пароль из настроек 98 | bool getPass(uint8_t* buff){ 99 | if(act_pass==false){ // нет установленного пароля 100 | return false; 101 | } 102 | // проверка типа пароля 103 | if(pas_in_hex){ 104 | for(uint8_t i=0;i<6;i++){ // пароль не в хексе !!! 105 | if(!((pass[i]>='0' && pass[i]<='9') || 106 | (pass[i]>='A' && pass[i]<='F') || 107 | (pass[i]>='a' && pass[i]<='f'))){ 108 | pas_in_hex=false; 109 | ESP_LOGE(TAG, "Password is not in HEX format, setting 'pas_in_hex' set to False!"); 110 | break; 111 | } 112 | } 113 | } 114 | if(pas_in_hex){ 115 | for(uint8_t i=0;i<6;i++){ 116 | if(pass[i]>='0' && pass[i]<='9'){ 117 | buff[i]=pass[i]-'0'; 118 | } else if (pass[i]>='A' && pass[i]<='F'){ 119 | buff[i]=pass[i]-'A'+10; 120 | } else if (pass[i]>='a' && pass[i]<='f'){ 121 | buff[i]=pass[i]-'a'+10; 122 | } 123 | } 124 | } else { 125 | for(uint8_t i=0;i<6;i++){ 126 | buff[i]=pass[i]; 127 | } 128 | } 129 | ESP_LOGD("This", "Password for send: %X,%X,%X,%X,%X,%X",buff[0],buff[1],buff[2],buff[3],buff[4],buff[5]); 130 | return true; 131 | } 132 | 133 | // открытие канала связи, безадресная 134 | void sConnect(){ 135 | sBuff->addr=addr; 136 | sBuff->packType=_OK; 137 | forSendSize = crc16mb(sendBuff, 4); // размер пакета 138 | forSendArrow = 0; 139 | forSenfType = GET_TEST; 140 | //esp_log_printf_(ESPHOME_LOG_LEVEL_ERROR, "HALLO", __LINE__, "sConnect"); 141 | } 142 | // загрузка пользовательского пароля в буфер 143 | void setpass(uint8_t* buff, uint32_t pass){ 144 | 145 | for(uint8_t i=0;i<6;i++){ 146 | 147 | } 148 | } 149 | 150 | // запрос доступа, по умолчанию с паролем пользователя 151 | void sAccess(){ 152 | sBuff->addr = addr; 153 | sBuff->packType=CONNECT; 154 | if(admin){ 155 | sBuff->data[0]=2; // уровень доступа 156 | if(act_pass){ 157 | getPass(sBuff->data+1); 158 | } else { 159 | //uint8_t pass[]=PASS_2; 160 | memcpy(sBuff->data+1, PASS_2, sizeof(PASS_2)); 161 | } 162 | } else { 163 | sBuff->data[0]=1; // уровень доступа 164 | if(act_pass){ 165 | getPass(sBuff->data+1); 166 | } else { 167 | //uint8_t pass[]=PASS_1; 168 | memcpy(sBuff->data+1,PASS_1, sizeof(PASS_1)); 169 | } 170 | } 171 | forSendSize = crc16mb(sendBuff, 11); 172 | forSendArrow = 0; 173 | forSenfType = GET_ACCESS; 174 | //esp_log_printf_(ESPHOME_LOG_LEVEL_ERROR, "HALLO", __LINE__, "sAccess"); 175 | } 176 | 177 | // предварительная подготовка к запросу параметров 6 байт 178 | void _getParam(uint8_t param){ 179 | sBuff->addr = addr; 180 | sBuff->packType = READ_PARAMS; 181 | sBuff->data[0]=(uint8_t)PARAM_ALL; 182 | sBuff->data[1]=param; 183 | forSendSize = crc16mb(sendBuff, 6); // возврат размера пакета 184 | forSendArrow = 0; 185 | } 186 | //мощность P, все фазы 187 | void sGetPower(){ _getParam(0); forSenfType = GET_POWER;} 188 | // напряжение, для группового запроса указываем первую фазу 189 | void sGetVoltage(){ _getParam(0x11); forSenfType = GET_VOLTAGE;}; 190 | // ток, для группового запроса указываем первую фазу 191 | void sGetCurrent(){ _getParam(0x21); forSenfType = GET_CURRENT;}; 192 | // коэффициетны мошности, для группового запроса указываем первую фазу 193 | void sGetKoefPower(){ _getParam(0x31); forSenfType = GET_KOEF_POWER;}; 194 | // запрос частоты 195 | void sGetFreq(){ _getParam(0x40); forSenfType = GET_FREQ;}; 196 | // углы, для группового запроса указываем первую фазу 197 | void sGetAnglePh(){_getParam(0x51); forSenfType = GET_ANGLE_PH;}; 198 | //запрос параметров устройства 199 | void sGetVers(){ 200 | sBuff->addr = addr; 201 | sBuff->packType = READ_PARAMS; 202 | sBuff->data[0]=1; 203 | forSendSize = crc16mb(sendBuff, 5); 204 | forSendArrow = 0; 205 | forSenfType = GET_VERS; 206 | } 207 | //запрос сетевого адреса 208 | void sGetAddr(){ 209 | sBuff->addr = 0; 210 | sBuff->packType = READ_PARAMS; 211 | sBuff->data[0] = 5; // параметр номер счетчика 212 | forSendSize = crc16mb(sendBuff, 5); 213 | forSendArrow = 0; 214 | forSenfType = GET_ADDR; 215 | //esp_log_printf_(ESPHOME_LOG_LEVEL_ERROR, "HALLO", __LINE__, "sGetAddr"); 216 | } 217 | // запрос показаний 218 | void sGetValue(){ 219 | sBuff->addr=addr; 220 | sBuff->packType = LIST; 221 | sBuff->data[0] =0; // энергия по сумме тарифов 222 | sBuff->data[1] = 0; // за весь период работы 223 | forSendSize = crc16mb(sendBuff,6); // возврат размера пакета 224 | forSendArrow = 0; 225 | forSenfType = GET_VALUE; 226 | } 227 | 228 | // возврат ошибок 229 | _replyReason getLastError(){ 230 | return lastError; 231 | } 232 | char* getStrError(_replyReason lastError){ 233 | static char out[27]={0}; 234 | char* rep=out; 235 | if((uint8_t)lastError & 0x80){ // это широковещалка 236 | lastError = (_replyReason)((uint8_t)lastError & 0x7F); 237 | strcpy(rep, "Broadcast "); 238 | rep+=10; //размер тега "Broadcast " 239 | } 240 | if(lastError==REP_OK){ 241 | strcpy(rep,"OK"); 242 | } else if (lastError==ERROR_COMMAND){ 243 | strcpy(rep,"Command error"); 244 | } else if (lastError==ERROR_HARDWARE){ 245 | strcpy(rep,"Hardware error"); 246 | } else if (lastError==ERROR_ACCESS_LEVEL){ 247 | strcpy(rep,"Access deny"); 248 | } else if (lastError==ERROR_CORE_TIME){ 249 | strcpy(rep,"Core time forbiden"); 250 | } else if (lastError==ERROR_CONNECTION){ 251 | strcpy(rep,"Connection close"); 252 | } else if(lastError==ERROR_TIMEOUT){ 253 | strcpy(rep,"Timeout error"); 254 | } else if(lastError==BUFFER_OVERFLOW){ 255 | strcpy(rep,"Buffer overflow"); 256 | } else { 257 | strcpy(rep,"Unexpected"); 258 | } 259 | return out; 260 | } 261 | 262 | // функции для публикации 263 | void _cbPower(float Psumm, float Pa, float Pb, float Pc){// будет вызвана при чтении из счетчика мощности 264 | static float _Pa=-_Pa; 265 | static float _Pb=-_Pb; 266 | static float _Pc=-_Pc; 267 | static float _Psumm=-_Psumm; 268 | if(this->Watts!=nullptr && _Psumm!=Psumm){_Psumm=Psumm; this->Watts->publish_state(Psumm);} 269 | if(this->WattA!=nullptr && _Pa!=Pa){_Pa=Pa; this->WattA->publish_state(Pa);} 270 | if(this->WattB!=nullptr && _Pb!=Pb){_Pb=Pb; this->WattB->publish_state(Pb);} 271 | if(this->WattC!=nullptr && _Pc!=Pc){_Pc=Pc; this->WattC->publish_state(Pc);} 272 | } 273 | void _cbVolt(float Va, float Vb, float Vc){// будет вызвана при чтении из счетчика напряжения 274 | static float _Va=_Va; 275 | static float _Vb=_Vb; 276 | static float _Vc=_Vc; 277 | if(this->VoltA!=nullptr && _Va!=Va){_Va=Va; this->VoltA->publish_state(Va);} 278 | if(this->VoltB!=nullptr && _Vb!=Vb){_Vb=Vb; this->VoltB->publish_state(Vb);} 279 | if(this->VoltC!=nullptr && _Vc!=Vc){_Vc=Vc; this->VoltC->publish_state(Vc);} 280 | } 281 | void _cbCurrent(float Ca, float Cb, float Cc){// будет вызвана при чтении из счетчика токов 282 | bool change_summ=false; 283 | static float _Ca=-_Ca; 284 | static float _Cb=-_Cb; 285 | static float _Cc=-_Cc; 286 | if(this->AmpA!=nullptr && _Ca!=Ca){_Ca=Ca; this->AmpA->publish_state(Ca); change_summ=true;} 287 | if(this->AmpB!=nullptr && _Cb!=Cb){_Cb=Cb; this->AmpB->publish_state(Cb); change_summ=true;} 288 | if(this->AmpC!=nullptr && _Cc!=Cc){_Cc=Cc; this->AmpC->publish_state(Cc); change_summ=true;} 289 | if(this->Amps!=nullptr && change_summ){this->Amps->publish_state(Ca+Cb+Cc);} 290 | } 291 | void _cbKoef(float Ra, float Rb, float Rc){// будет вызвана при чтении коэфициентов 292 | static float _Ra=-_Ra; 293 | static float _Rb=-_Rb; 294 | static float _Rc=-_Rc; 295 | if(this->RatioA!=nullptr && _Ra!=Ra){_Ra=Ra; this->RatioA->publish_state(Ra);} 296 | if(this->RatioB!=nullptr && _Rb!=Rb){_Rb=Rb; this->RatioB->publish_state(Rb);} 297 | if(this->RatioC!=nullptr && _Rc!=Rc){_Rc=Rc; this->RatioC->publish_state(Rc);} 298 | } 299 | void _cbAngles(float Aa, float Ab, float Ac){// будет вызвана при чтении фазовых сдвигов 300 | static float _Aa=-_Aa; 301 | static float _Ab=-_Ab; 302 | static float _Ac=-_Ac; 303 | if(this->AngleA!=nullptr && _Aa!=Aa){_Aa=Aa; this->AngleA->publish_state(Aa);} 304 | if(this->AngleB!=nullptr && _Ab!=Ab){_Ab=Ab; this->AngleB->publish_state(Ab);} 305 | if(this->AngleC!=nullptr && _Ac!=Ac){_Ac=Ac; this->AngleC->publish_state(Ac);} 306 | } 307 | void _cbFreq(float Fr){// будет вызвана когда счетчик ответит на запрос о частоте 308 | static float _Fr=0; 309 | if(this->Freq!=nullptr && _Fr!=Fr){_Fr=Fr; this->Freq->publish_state(Fr);} 310 | } 311 | void _cbValues(float Aa, float Ar){// будет вызвана при получении показаний 312 | static float _Aa=-_Aa; 313 | static float _Ar=-_Ar; 314 | if(this->ValueA!=nullptr && _Aa!=Aa){_Aa=Aa; this->ValueA->publish_state(Aa);} 315 | if(this->ValueR!=nullptr && _Ar!=Ar){_Ar=Ar; this->ValueR->publish_state(Ar);} 316 | } 317 | // для трансляции принятого пакета 318 | void inDataReady(uint8_t size, uint8_t* buff){ 319 | memcpy(inPacket,buff,size); 320 | sizeInPacket=size; 321 | } 322 | // для трансляции отправляемого пакета 323 | void outDataReady(uint8_t size, uint8_t* buff){ 324 | memcpy(outPacket,buff,size); 325 | sizeOutPacket=size; 326 | } 327 | 328 | // разбор полученного пакета 329 | void parceInbound(){ 330 | if(debugIn){ // показываем буфер для отладки 331 | outDataReady(fromReadArrow, readBuff); 332 | } 333 | if(readBuff[0] == addr || readBuff[0] == 0){ // только если ответ от нашего счетчика 334 | uint32_t temp; 335 | if(fromReadArrow == 4){ // 4 байта скорее всего это пакет подтверждение 336 | lastError=(_replyReason)readBuff[1]; 337 | if(lastError!=REP_OK && lastError!=ERROR_CORE_TIME){ 338 | procError=true; // ошибка связи 339 | } 340 | if(readBuff[0] == 0){ 341 | lastError=(_replyReason)(readBuff[1] | 0x80);// те же ошибки с флагом широковещалки 342 | } 343 | fromReadArrow=0; 344 | } else if(fromReadArrow == 5){ // 5 байтовый входящий 345 | if(forSenfType == GET_ADDR){ 346 | addr=readBuff[2]; // ответ на запрос сетевого адреса 347 | fromReadArrow=0; 348 | lastError=REP_OK; 349 | } 350 | } else if(fromReadArrow == 15){ // пакет 4x3 351 | if(forSenfType == GET_POWER){ // ответ на запрос энергии 352 | fromReadArrow=0; 353 | lastError=REP_OK; 354 | _cbPower((float)dm32_3(readBuff+1)/100, 355 | (float)dm32_3(readBuff+4)/100, 356 | (float)dm32_3(readBuff+7)/100, 357 | (float)dm32_3(readBuff+10)/100); 358 | } 359 | } else if(fromReadArrow == 12){ // пакет 3x3 360 | if(forSenfType == GET_VOLTAGE){ // ответ на запрос напряжения 361 | fromReadArrow=0; 362 | lastError=REP_OK; 363 | _cbVolt((float)dm32_3(readBuff+1)/100, 364 | (float)dm32_3(readBuff+4)/100, 365 | (float)dm32_3(readBuff+7)/100); 366 | } else if (forSenfType == GET_KOEF_POWER){ // ответ на запрос коэфициентов 367 | fromReadArrow=0; 368 | lastError=REP_OK; 369 | _cbKoef((float)dm32_3(readBuff+1)/100, 370 | (float)dm32_3(readBuff+4)/100, 371 | (float)dm32_3(readBuff+7)/100); 372 | } else if (forSenfType == GET_ANGLE_PH){ // ответ на запрос углов 373 | fromReadArrow=0; 374 | lastError=REP_OK; 375 | _cbAngles((float)dm32_3(readBuff+1)/100, 376 | (float)dm32_3(readBuff+4)/100, 377 | (float)dm32_3(readBuff+7)/100); 378 | } else if (forSenfType == GET_CURRENT){ // ответ на запрос тока 379 | fromReadArrow=0; 380 | lastError=REP_OK; 381 | _cbCurrent((float)dm32_3(readBuff+1)/1000, 382 | (float)dm32_3(readBuff+4)/1000, 383 | (float)dm32_3(readBuff+7)/1000); 384 | } 385 | } else if (fromReadArrow == 6){ // 6 байт 386 | if (forSenfType == GET_FREQ){ // ответ на запрос частоты 387 | fromReadArrow=0; 388 | lastError=REP_OK; 389 | _cbFreq((float)dm32_3(readBuff+1)/100); 390 | } 391 | } else if (fromReadArrow == 19){ // 19 байт 392 | if (forSenfType == GET_VERS){ 393 | char temp[15]={0}; 394 | // получаем серийный номер 395 | if(this->sn_string!=nullptr){ //серийный номер 396 | snprintf(temp, sizeof(temp)-1, "%02d%02d%02d%02d",readBuff[1],readBuff[2],readBuff[3],readBuff[4]); 397 | this->sn_string->publish_state(temp); 398 | } 399 | if(this->vers_string!=nullptr){ //версия прибора 400 | snprintf(temp, sizeof(temp)-1, "%d.%02d.%02d",readBuff[8],readBuff[9],readBuff[10]); 401 | this->vers_string->publish_state(temp); 402 | } 403 | if(this->fab_date_string!=nullptr){ //дата изготовления 404 | snprintf(temp, sizeof(temp)-1, "%d/%02d/%02d",readBuff[5],readBuff[6],readBuff[7]); 405 | this->fab_date_string->publish_state(temp); 406 | } 407 | fromReadArrow=0; 408 | lastError=REP_OK; 409 | } else if (forSenfType == GET_VALUE){ // показания счетчика Активные, Реактивные 410 | fromReadArrow=0; 411 | lastError=REP_OK; 412 | _cbValues((float)dm32_4(readBuff+1)/1000, (float)dm32_4(readBuff+9)/1000); 413 | } 414 | } else if (fromReadArrow == 17){ //17 байт 415 | //... 416 | } 417 | } else { // данные чужого счетчика 418 | fromReadArrow=0; // сбрасываем данные 419 | lastError=REP_OK; 420 | } 421 | } 422 | 423 | void setupMerc(uint32_t _scanPeriod){ // установка начальных параметров 424 | scanPeriod = _scanPeriod; // корректировка на время обработки 425 | scanTimer = millis() - _scanPeriod; // инициализация таймера опроса 426 | } 427 | 428 | void setUpdatePeriod(uint32_t period){ // изменение периода на лету 429 | if(period < MIN_SCAN_PERIOD){period = MIN_SCAN_PERIOD;} 430 | scanPeriod = period; 431 | } 432 | 433 | // коннектор исходящих данных 434 | // проверка наличия данных для отправки, за одно цикл обработки 435 | uint8_t availableMerc(){ 436 | uint32_t _now=millis(); 437 | static uint8_t counter=0; 438 | 439 | // КОНТРОЛЬ НЕ ОТВЕТА 440 | if(waiteReply && _now-timeReadByte>ABORT_RECIVE_TIME){ // отслеживаем таймаут приема байта 441 | waiteReply = false; 442 | if(counter>5){ // поднимаем ошибки только на запросах данных 443 | lastError=ERROR_TIMEOUT; 444 | } 445 | procError=true; // поднимаем ошибку для повтора цикла инициализации 446 | } 447 | 448 | // если в буфере есть данные - показать их количесто 449 | uint8_t ret=forSendSize-forSendArrow; 450 | if(ret){ // если есть данные для отправки 451 | return ret; //ничего не делаем 452 | } 453 | 454 | // ЦИКЛ ОБРАБОТКИ 455 | if(_now-scanTimer>=scanPeriod){ // таймер шиклов опроса 456 | if(!waiteReply && _now-timeSendByte>=PACKET_MIN_DELAY){ // ТАЙМЕР МЕЖПАкЕТНОГО ИНТРЕВАЛА, одновременно ждем ответ 457 | timeSendByte=_now; 458 | while(counter<=10){ 459 | if (counter==0){sConnect(); break;} // на нулевом шаге пожимаем руку 460 | else if (counter==1){sAccess(); break;} // далее просим доступ 461 | // поиск адреса только если он нулевой и пока не найдем дальше не работаем 462 | else if (counter==2 && addr==0){sGetAddr(); counter=11; procError=true; break;} 463 | else if (counter==3){sGetVers(); break;} // далее версию, дату изготовления, серийник 464 | else if (counter==4){if(cbValues){sGetValue(); break;}} // показания 465 | else if (counter==5){if(cbPower){sGetPower(); break;}} // на этом шаге можем считать мощность 466 | else if (counter==6){if(cbVolt){sGetVoltage(); break;}} // вольты 467 | else if (counter==7){if(cbCurrent){sGetCurrent(); break;}} // ток 468 | else if (counter==8){if(cbKoef){sGetKoefPower(); break;}} // коэфициенты 469 | else if (counter==9){if(cbAngles){sGetAnglePh(); break;}} // углы 470 | else if (counter==10){if(cbFreq){sGetFreq(); break;}} // частота 471 | counter++; 472 | } 473 | if(counter++>10){ // зацикливание счетчика 474 | if(_now-scanTimer>2*scanPeriod){ // еСЛИ ВРЕМЯ ПЕРИОДА прешышает требуемое значительно 475 | scanTimer=_now; // то сбрасываем таймер - пофиг регулярность 476 | } else { 477 | scanTimer+=scanPeriod; // так мы учитываем уже отработанное время точно 478 | } 479 | if(procError){ // если в цикле была ошибка при связи 480 | procError=false; 481 | counter=0; // пройдем весь цикл запросов, возможно снова нужна авторизация 482 | } else { 483 | counter=3; // если без ошибок, то повторной инициализации не нужно, просто опросим параметры 484 | } 485 | } 486 | } 487 | } else { 488 | timeReadByte=_now; // для сброса ложной ошибки таймаута получения ответа 489 | } 490 | return forSendSize-forSendArrow; // возможно в буфере появились данные 491 | } 492 | 493 | //отдача байта счетчику 494 | uint8_t getByteForMerc(){ 495 | if(forSendSize-forSendArrow){ //если буфер не пустой 496 | waiteReply = true; 497 | uint8_t ret=sendBuff[forSendArrow++]; 498 | if(forSendSize-forSendArrow==0){ 499 | forSendSize=0; 500 | forSendArrow=0; 501 | } 502 | return ret; 503 | } 504 | return 0; 505 | } 506 | 507 | //отдача буфера счетчику 508 | uint8_t* getBuffForMerc(){ 509 | uint8_t* ret= &(sendBuff[forSendArrow]); 510 | forSendArrow=0; 511 | forSendSize=0; 512 | return ret; 513 | } 514 | 515 | // входящий байт пихаем сюда 516 | _replyReason getFromMerc(uint8_t d){ 517 | uint32_t _now=millis(); 518 | if(_now-timeReadByte>ABORT_RECIVE_TIME){ // таймаут получения данных 519 | goto reset_buff; //ошибку не поднимаем, нужно только для корректности данных 520 | } 521 | if(fromReadArrow == sizeof(readBuff)){ // переполнение буфера 522 | procError=true; // поднимаем ошибку для повтора цикла инициализации 523 | lastError = BUFFER_OVERFLOW; 524 | reset_buff: 525 | fromReadArrow=0; // сбрасываем уже не нужные данные 526 | } 527 | waiteReply = false; // снимаем флаг ожидания ответа, что то получили 528 | timeReadByte=_now; // засекаем время получения байта 529 | readBuff[fromReadArrow++]=d; // кладем байт в буфер 530 | if(fromReadArrow==1){ // если это начало пакета 531 | stepCrc16mb(d, true); // начнем счикать КС 532 | } else if( fromReadArrow <3){ // размер данных еще не достаточен для КС + данные 533 | stepCrc16mb(d); 534 | } else { // если получили пакет больше 2 байт+CS 535 | if(stepCrc16mb(d) == 0){ //вероятный конец данных контрольная сумма обнулилась !!! 536 | parceInbound(); 537 | availableMerc(); // обслужить буфер для очистки 538 | } 539 | } 540 | return lastError; 541 | } 542 | 543 | #endif //MERCURY230_PROTO_H 544 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------