├── CHANGELOG ├── img └── ups-ha.png ├── fanShutDownUps.ini ├── launcher.sh ├── setProtectionVoltage.py ├── setSampleInterval.py ├── .gitattributes ├── HA_config_ups_fan.yaml ├── .gitignore ├── README.md ├── LICENSE └── fanShutDownUps.py /CHANGELOG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frtz13/UPSPlus_mqtt/HEAD/CHANGELOG -------------------------------------------------------------------------------- /img/ups-ha.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frtz13/UPSPlus_mqtt/HEAD/img/ups-ha.png -------------------------------------------------------------------------------- /fanShutDownUps.ini: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frtz13/UPSPlus_mqtt/HEAD/fanShutDownUps.ini -------------------------------------------------------------------------------- /launcher.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # launcher.sh 3 | 4 | python3 /home/pi/scripts/fanShutDownUps.py & 5 | -------------------------------------------------------------------------------- /setProtectionVoltage.py: -------------------------------------------------------------------------------- 1 | 2 | # adapted from UPSPlus upsPlus.py script by frtz13@github.com 3 | 4 | import os 5 | import sys 6 | import smbus2 7 | 8 | # Define I2C bus 9 | DEVICE_BUS = 1 10 | 11 | # Define device i2c slave address. 12 | DEVICE_ADDR = 0x17 13 | 14 | print("-"*60) 15 | print("Modify battery protection voltage in UPS Plus") 16 | print("-"*60) 17 | 18 | PV_Mini_mV = 3000 19 | PV_Maxi_mV = 4000 20 | 21 | # Raspberry Pi Communicates with MCU via i2c protocol. 22 | bus = smbus2.SMBus(DEVICE_BUS) 23 | currentProtectionVoltage_mV = bus.read_byte_data(DEVICE_ADDR, 0x12) << 8 | bus.read_byte_data(DEVICE_ADDR, 0x11) 24 | print("Current value: %d mV" % currentProtectionVoltage_mV) 25 | 26 | if len(sys.argv) > 1: 27 | try: 28 | givenPV_mV = int(sys.argv[1]) 29 | if givenPV_mV >= PV_Mini_mV and givenPV_mV <= PV_Maxi_mV : 30 | bus.write_byte_data(DEVICE_ADDR, 0x11, givenPV_mV & 0xFF) 31 | bus.write_byte_data(DEVICE_ADDR, 0x12, (givenPV_mV >> 8)& 0xFF) 32 | print("Successfully set the protection voltage to: %d mV" % givenPV_mV) 33 | else: 34 | errMsg = "Protection voltage should be given between {:.0f} and {:.0f} mV".format(PV_Mini_mV, PV_Maxi_mV) 35 | print(errMsg) 36 | except Exception as exc: 37 | print("Incorrect parameter: {}. ({})".format(sys.argv[1], str(exc))) 38 | else: 39 | print("Usage: {} ".format(sys.argv[0])) 40 | print(" between {:.0f} and {:.0f}".format(PV_Mini_mV,PV_Maxi_mV)) -------------------------------------------------------------------------------- /setSampleInterval.py: -------------------------------------------------------------------------------- 1 | 2 | # adapted from UPSPlus upsPlus.py script by frtz13@github.com 3 | 4 | import os 5 | import sys 6 | import smbus2 7 | 8 | # Define I2C bus 9 | DEVICE_BUS = 1 10 | 11 | # Define device i2c slave address. 12 | DEVICE_ADDR = 0x17 13 | 14 | print("-"*60) 15 | print("Modify sample interval in UPS Plus") 16 | print("-"*60) 17 | 18 | SAMPLEINTERVAL_MINI_min = 2 19 | SAMPLEINTERVAL_MAX_min = 120 20 | 21 | # Raspberry Pi Communicates with MCU via i2c protocol. 22 | bus = smbus2.SMBus(DEVICE_BUS) 23 | current_sample_interval_min = bus.read_byte_data(DEVICE_ADDR, 0x16) << 8 | bus.read_byte_data(DEVICE_ADDR, 0x15) 24 | print(f"Current value: {current_sample_interval_min} min") 25 | 26 | if len(sys.argv) > 1: 27 | try: 28 | given_si_min = int(sys.argv[1]) 29 | if given_si_min >= SAMPLEINTERVAL_MINI_min and given_si_min <= SAMPLEINTERVAL_MAX_min : 30 | bus.write_byte_data(DEVICE_ADDR, 0x15, given_si_min & 0xFF) 31 | bus.write_byte_data(DEVICE_ADDR, 0x16, 0) 32 | print(f"Successfully set the sample interval to: {given_si_min} min") 33 | else: 34 | errMsg = f"Sample interval should be given between {SAMPLEINTERVAL_MINI_min:.0f} and {SAMPLEINTERVAL_MAX_min:.0f} min" 35 | print(errMsg) 36 | except Exception as exc: 37 | print(f"Incorrect parameter: {sys.argv[1]}. ({str(exc)})") 38 | else: 39 | print(f"Usage: {sys.argv[0]} ") 40 | print(f" between {SAMPLEINTERVAL_MINI_min:.0f} and {SAMPLEINTERVAL_MAX_min:.0f}") -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /HA_config_ups_fan.yaml: -------------------------------------------------------------------------------- 1 | # example file for Home Assistant sensor definitions 2 | # copy / paste sensor definitions of interest to your own configuration.yaml file 3 | 4 | mqtt: 5 | sensor: 6 | - name: CPU fan speed 7 | unit_of_measurement: "%" 8 | state_topic: "home/rpi/fanspeed" 9 | availability: 10 | - topic: "home/rpi/LWT" 11 | payload_available: "online" 12 | payload_not_available: "offline" 13 | 14 | - name: "UPS Battery Voltage" 15 | device_class: voltage 16 | state_topic: "home/rpi/ups" 17 | value_template: '{{ value_json["BatteryVoltage_V"] }}' 18 | unit_of_measurement: "V" 19 | availability: 20 | - topic: "home/rpi/LWT" 21 | payload_available: "online" 22 | payload_not_available: "offline" 23 | 24 | - name: "UPS Battery current" 25 | device_class: current 26 | state_topic: "home/rpi/ups" 27 | value_template: '{{ value_json["BatteryCurrent_A"] }}' 28 | unit_of_measurement: "A" 29 | availability: 30 | - topic: "home/rpi/LWT" 31 | payload_available: "online" 32 | payload_not_available: "offline" 33 | 34 | - name: "UPS average Battery current" 35 | device_class: current 36 | state_topic: "home/rpi/ups" 37 | value_template: '{{ value_json["BatteryCurrent_avg_A"] }}' 38 | unit_of_measurement: "A" 39 | availability: 40 | - topic: "home/rpi/LWT" 41 | payload_available: "online" 42 | payload_not_available: "offline" 43 | 44 | - name: "UPS average Battery power" 45 | device_class: power 46 | state_topic: "home/rpi/ups" 47 | value_template: '{{ value_json["BatteryPower_avg_W"] }}' 48 | unit_of_measurement: "W" 49 | availability: 50 | - topic: "home/rpi/LWT" 51 | payload_available: "online" 52 | payload_not_available: "offline" 53 | 54 | - name: "UPS Battery temperature" 55 | device_class: temperature 56 | state_topic: "home/rpi/ups" 57 | value_template: '{{ value_json["BatteryTemperature_degC"] }}' 58 | unit_of_measurement: "°C" 59 | availability: 60 | - topic: "home/rpi/LWT" 61 | payload_available: "online" 62 | payload_not_available: "offline" 63 | 64 | - name: "UPS Output Voltage" 65 | device_class: voltage 66 | state_topic: "home/rpi/ups" 67 | value_template: '{{ value_json["OutputVoltage_V"] }}' 68 | unit_of_measurement: "V" 69 | availability: 70 | - topic: "home/rpi/LWT" 71 | payload_available: "online" 72 | payload_not_available: "offline" 73 | 74 | - name: "UPS minimum Output Voltage" 75 | device_class: voltage 76 | state_topic: "home/rpi/ups" 77 | value_template: '{{ value_json["OutputVoltage_mini_V"] }}' 78 | unit_of_measurement: "V" 79 | availability: 80 | - topic: "home/rpi/LWT" 81 | payload_available: "online" 82 | payload_not_available: "offline" 83 | 84 | - name: "UPS Output current" 85 | device_class: current 86 | state_topic: "home/rpi/ups" 87 | value_template: '{{ value_json["OutputCurrent_A"] }}' 88 | unit_of_measurement: "A" 89 | availability: 90 | - topic: "home/rpi/LWT" 91 | payload_available: "online" 92 | payload_not_available: "offline" 93 | 94 | - name: "UPS average output current" 95 | device_class: current 96 | state_topic: "home/rpi/ups" 97 | value_template: '{{ value_json["OutputCurrent_avg_A"] }}' 98 | unit_of_measurement: "A" 99 | availability: 100 | - topic: "home/rpi/LWT" 101 | payload_available: "online" 102 | payload_not_available: "offline" 103 | 104 | - name: "UPS peak output current" 105 | device_class: current 106 | state_topic: "home/rpi/ups" 107 | value_template: '{{ value_json["OutputCurrent_peak_A"] }}' 108 | unit_of_measurement: "A" 109 | availability: 110 | - topic: "home/rpi/LWT" 111 | payload_available: "online" 112 | payload_not_available: "offline" 113 | 114 | - name: "UPS average output power" 115 | device_class: power 116 | state_topic: "home/rpi/ups" 117 | value_template: '{{ value_json["OutputPower_avg_W"] }}' 118 | unit_of_measurement: "W" 119 | availability: 120 | - topic: "home/rpi/LWT" 121 | payload_available: "online" 122 | payload_not_available: "offline" 123 | 124 | - name: "UPS Battery Remaining Capacity" 125 | device_class: energy 126 | state_topic: "home/rpi/ups" 127 | value_template: '{{ value_json["BatteryRemainingCapacity_percent"] }}' 128 | unit_of_measurement: "%" 129 | availability: 130 | - topic: "home/rpi/LWT" 131 | payload_available: "online" 132 | payload_not_available: "offline" 133 | 134 | - name: "UPS IOT Platform reply" 135 | state_topic: "home/rpi/ups" 136 | value_template: '{{ value_json["UPSPlus_IOT_Platform_Reply"] }}' 137 | availability: 138 | - topic: "home/rpi/LWT" 139 | payload_available: "online" 140 | payload_not_available: "offline" 141 | 142 | binary_sensor: 143 | # please note that this sensor gets the whole set of values as attributes 144 | # you can move the json_attributes_topic line to any other sensor definition 145 | - name: "UPS healthy" 146 | state_topic: "home/rpi/ups" 147 | value_template: '{{ value_json["IsHealthy"] }}' 148 | payload_on: true 149 | payload_off: false 150 | availability: 151 | - topic: "home/rpi/LWT" 152 | payload_available: "online" 153 | payload_not_available: "offline" 154 | json_attributes_topic: "home/rpi/ups" 155 | 156 | - name: "UPS on Battery" 157 | state_topic: "home/rpi/ups" 158 | value_template: '{{ value_json["OnBattery"] }}' 159 | payload_on: true 160 | payload_off: false 161 | json_attributes_topic: "home/rpi/ups" 162 | availability: 163 | - topic: "home/rpi/LWT" 164 | payload_available: "online" 165 | payload_not_available: "offline" 166 | 167 | - name: "UPS Battery Charging" 168 | state_topic: "home/rpi/ups" 169 | value_template: '{{ value_json["BatteryCharging"] }}' 170 | payload_on: true 171 | payload_off: false 172 | availability: 173 | - topic: "home/rpi/LWT" 174 | payload_available: "online" 175 | payload_not_available: "offline" 176 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd 364 | 365 | # solution/project files 366 | *.pyproj 367 | *.sln -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Background script for Raspberry Pi and UPSPlus (52pi) for automatic shutdown, UPS status to MQTT, fan control 2 | 3 | ## Purpose of the script 4 | 5 | - Runs in the background, launched as cronjob at boot time. 6 | 7 | - Checks UPS and battery status. Shuts down the Raspberry Pi when battery voltage is under configured threshold. 8 | 9 | - Can control a fan via a GPIO pin using PWM, depending on CPU temperature. 10 | 11 | - Can publish UPS status and fan status data to a MQTT broker. 12 | 13 | - Can send UPS status data to the manufacturer's IOT platform. 14 | 15 | ## Requirements 16 | 17 | - a Geekpi UPSPlus EP-0136 (52pi) 18 | 19 | - python3 20 | 21 | - additional modules: RPi.GPIO, smbus2, pi-ina219, paho-mqtt, requests 22 | 23 | ## Installation 24 | 25 | - Install python3 if it isn't already installed. 26 | 27 | - Install additional modules via: pip3 install _module-name_ 28 | 29 | - Copy fanShutDownUps.py, fanShutDownUps.ini, launcher.sh into a folder (we use ~/scripts in our example) 30 | 31 | ``` 32 | wget https://raw.githubusercontent.com/frtz13/UPSPlus_mqtt/master/fanShutDownUps.py 33 | ``` 34 | 35 | etc. for the other files. 36 | 37 | - Create a folder ~/logs 38 | 39 | - Configure your options in fanShutDownUps.ini (please see below for details) 40 | 41 | - When ready, install to crontab: 42 | `crontab -e` 43 | then add the line: 44 | 45 | ``` 46 | @reboot sh /home/pi/scripts/launcher.sh >/home/pi/logs/cronlog 2>&1 47 | ``` 48 | 49 | ## Configuration 50 | 51 | #### Fan 52 | 53 | If you want to use this option, please read Andreas Spiess' excellent article [SensorsIOT: Variable cooling fan for Raspberry Pi](https://www.sensorsiot.org/variable-speed-cooling-fan-for-raspberry-pi-using-pwm-video138/) about how to assemble the required hardware. The script can also send the fan speed percentage to your MQTT broker (default topic: `home/rpi/fanspeed`) 54 | 55 | Configuration parameters: 56 | 57 | **GPIO_FAN**: GPIO pin number to control the fan. Set to -1 to disable fan control completely. 58 | 59 | **FAN_LOOP_TIME_s**: recommended value: 5. Interval for fan speed calculation. 60 | 61 | **DESIRED_CPU_TEMP_degC**: the fan control will start to work at this temperature and try to maintain this CPU temperature. This parameter is re-read at runtime with the `BATTERY_CHECK_LOOP_TIME_s` interval, so you can change this value on the fly, to check if fan control is working properly. 62 | 63 | #### UPS 64 | 65 | At startup, the script will check if it can detect the UPS at the expected address on the i2c-bus, and deactivate communication with the UPS if the UPS does not respond. 66 | 67 | **SEND_STATUS_TO_UPSPLUS_IOT_PLATFORM**: setting this to 1 will do the same job as the upsplus_iot.py script in https://github.com/geeekpi/upsplus. Set to 0 to avoid sending the data. 68 | 69 | **UPSPLUS_IOT_PLATFORM_URL**: lets you specify the feed URL. If you don't, https://api.52pi.com/feed will be used. 70 | 71 | **BATTERY_CHECK_LOOP_TIME_s**: recommended value: 60. Interval for battery check and transmission of the UPS status to the MQTT broker. 72 | 73 | **SHUTDOWN_TIMEOUT_s**: recommended value: 30 or 60, depending on how much time your Raspberry Pi needs to safely shut down. 74 | 75 | **PROTECTION_VOLTAGE_MARGIN_mV**: recommended value: 200. Shutdown will be triggered when the battery voltage is lower than the sum of the UPS-Plus protection voltage and this value. 76 | 77 | Later you may want to adjust the INA_219_SHUNT... parameters to calibrate the current readings. I did this by measuring the USB charger current while the batteries are fully charged, and assuming some reasonable efficiency factor for the UPS circuits. 78 | 79 | #### MQTT broker 80 | 81 | Configuration parameters for the MQTT broker should be self-explaining. If you do not want to use this feature, set BROKER to an empty value. 82 | 83 | ## Operation 84 | 85 | I decided to write a script running continuously in the background to avoid having crontab messages every minute or so in my syslog. Putting all the functions into one script will also ensure that i2c registers will not be accessed concurrently. 86 | 87 | #### Automatic shutdown 88 | 89 | When the UPS Plus is on battery, a message is written every minute to the syslog, containing the current battery voltage and the critical limit. "On battery" status is assumed when the average battery discharge current is greater than 500mA. Because of the use of the average current, status changes will be recognized with some delay. 90 | 91 | When the measured battery voltage goes under the critical value while the UPS is on battery, the shutdown is triggered: the UPSPlus Back-To-AC-auto-power-up parameter is set, the UPSPlus shutdown countdown is started, and the Raspberry Pi is told to shut down. Thus, the Raspberry Pi should restart once AC power is back and the batteries charge again. 92 | 93 | At startup, the script will not check the battery voltage during the first five minutes, to avoid another immediate shutdown if AC power comes back with some instability. 94 | 95 | In addition, MQTT data will not be published during this time to leave time for the MQTT broker to start up if it runs on the same Raspberry Pi. That said, the script is supposed to reconnect to the MQTT broker in case the latter stops and restarts. 96 | 97 | Therefore, in a worst case scenario where cron starts the script at boot time, if erroneous values are read from the UPS Plus, or something else is wrong with the script, you should have enough time to kill the script before it attempts to shut down your Raspberry Pi. 98 | 99 | #### MQTT 100 | 101 | Fan data is published to the broker with the topic `home/rpi/fanspeed` (depending on your configuration). Fan PWM ratio in percent is sent every 5 seconds (by default), but only when its value changes. It is sent with the "retain" flag set. 102 | 103 | UPS data is published to the broker with the topic `home/rpi/ups`. It is sent as a json string. Included values are: 104 | 105 | - UsbC_V, 106 | 107 | - UsbMicro_V, 108 | 109 | - OnBattery (boolean; `true` when average discharging current is greater than 500mA; `false` otherwise), 110 | 111 | - BatteryVoltage_V (as measured by the INA219 sensor at i2c address 0x45), 112 | 113 | - BatteryCurrent_A (positive value: discharging, negative value: charging) 114 | 115 | - BatteryCurrent_avg_A, 116 | 117 | - BatteryPower_avg_W, 118 | 119 | - BatteryCharging (boolean, `true` if BatteryCurrent_avg_A is negative) 120 | 121 | - BatteryRemainingCapacity_percent, 122 | 123 | - BatteryTemperature_degC, 124 | 125 | - OutputVoltage_V (as measured by the INA219 sensor at i2c address 0x40), 126 | 127 | - OutputVoltage_mini_V (minimum value during the preceding time interval of BATTERY_CHECK_LOOP_TIME_s) 128 | 129 | - OutputCurrent_A, 130 | 131 | - OutputCurrent_avg_A, 132 | 133 | - OutputPower_avg_W, 134 | 135 | - OutputCurrent_peak_mA (peak value during the preceding time interval of BATTERY_CHECK_LOOP_TIME_s) 136 | 137 | Measurements are averaged over a time interval twice as long as BATTERY_CHECK_LOOP_TIME_s. 138 | 139 | ##### Using the MQTT data 140 | 141 | As an example, if you want to get your data into Home Assistant, you can define sensors in the Home Assistant configuration file: 142 | 143 | ``` 144 | sensor: 145 |   - platform: mqtt 146 |     name: "UPS average battery current" 147 |     device_class: current 148 |     state_topic: "home/rpi/ups" 149 |     value_template: '{{ value_json["BatteryCurrent_avg_A"] }}' 150 |     unit_of_measurement: "A" 151 |     availability: 152 |       - topic: "home/rpi/LWT" 153 |         payload_available: "online" 154 |         payload_not_available: "offline" 155 | ``` 156 | 157 | or 158 | 159 | ``` 160 | binary_sensor: 161 | - platform: mqtt 162 | name: "UPS on Battery" 163 | state_topic: "home/rpi/ups" 164 | value_template: '{{ value_json["OnBattery"] }}' 165 | payload_on: "True" 166 | payload_off: "False" 167 | availability: 168 | - topic: "home/rpi/LWT" 169 | payload_available: "online" 170 | payload_not_available: "offline" 171 | ``` 172 | 173 | You'll find more sensor definitions in the `HA_config_ups_fan.yaml` file. 174 | 175 | ![](./img/ups-ha.png) 176 | 177 | ### Getting things ready 178 | 179 | For a first try, you may want to start the script with the `--notimerbias` command line argument. Alternatively, you can set the following parameter in your configuration file, [ups] section: `TIMER_BIAS_AT_STARTUP = 0`. This will instruct the script to start the UPS probing immediately, without waiting for five minutes. 180 | 181 | Start the script: `python3 fanShutDownUps.py` 182 | 183 | If any dependencies are missing, you will get corresponding error messages. 184 | 185 | You can stop the script with ctrl-C. 186 | 187 | If you do not get any error messages, switch off AC power for the UPS and have a look at the syslog (`journalctl -f`). After a minute or two, you should get a message that the UPS is on battery. 188 | 189 | If you configured a connection to an MQTT broker, start up an MQTT client and have it listen to the `home/rpi/#` topic. 190 | 191 | If you want to simulate a shutdown at low battery voltage, do the following in order to avoid to have to wait for a low battery situation: 192 | 193 | Be sure to have AC power for the UPS switched on. Start the script with the `--shutdowntest` argument (or set the following parameter in your configuration file, [ups] section: `SHUTDOWN_IMMEDIATELY_WHEN_ON_BATTERY = 1`), and restart the script. This will instruct the script to start a shutdown sequence immediately, as soon as the UPS is on battery. Once the shutdown sequence completed and the UPS shut down power for the Raspberry Pi, you can restore AC power. The UPS should switch on, and the Raspberry Pi should start. 194 | 195 | Once you are done with testing, comment out the `TIMER_BIAS_AT_STARTUP` and `SHUTDOWN_IMMEDIATELY_WHEN_ON_BATTERY` parameters in the configuration file if you used them for testing, configure crontab to start the script at boot time and restart your Raspberry Pi. 196 | 197 | With the v10 firmware of the UPS, you will get syslog messages such as "Error getting data from UPS...Remote I/O error" from time to time. Don't worry about these, as long you do not get more than a couple of them per hour. 198 | 199 | ## References 200 | 201 | [UPS Plus SKU: EP-0136 - 52Pi Wiki](https://wiki.52pi.com/index.php/UPS_Plus_SKU:_EP-0136) 202 | 203 | https://github.com/geeekpi/upsplus 204 | 205 | https://www.sensorsiot.org/variable-speed-cooling-fan-for-raspberry-pi-using-pwm-video138/ 206 | 207 | http://www.steves-internet-guide.com/into-mqtt-python-client/ 208 | -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | -------------------------------------------------------------------------------- /fanShutDownUps.py: -------------------------------------------------------------------------------- 1 | 2 | #!/usr/bin/env python3 3 | 4 | # Copyright (C) 2021 frtz13.github.com 5 | 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | 19 | # fan control function: thanks to Andreas Spiess https://www.sensorsiot.org/variable-speed-cooling-fan-for-raspberry-pi-using-pwm-video138/ 20 | # mqtt publishing : many thanks to http://www.steves-internet-guide.com/into-mqtt-python-client/ 21 | # UPSPlus: https://github.com/geeekpi/upsplus 22 | 23 | import os 24 | import time 25 | from time import sleep 26 | # import logging 27 | # import signal 28 | import sys 29 | import json 30 | import configparser 31 | # import random 32 | from collections import deque 33 | import syslog 34 | import requests 35 | import itertools as it 36 | 37 | import RPi.GPIO as GPIO 38 | import smbus2 39 | from ina219 import INA219,DeviceRangeError 40 | import paho.mqtt.client as mqtt 41 | 42 | SCRIPT_VERSION = "2025.04.02" 43 | 44 | CONFIG_FILE = "fanShutDownUps.ini" 45 | CONFIGSECTION_FAN = "fan" 46 | CONFIGSECTION_MQTT = "mqtt" 47 | CONFIGSECTION_UPS = "ups" 48 | 49 | CMD_NO_TIMER_BIAS = "--notimerbias" 50 | CMD_SHUTDOWN_IMMEDIATELY_WHEN_ON_BATTERY = "--shutdowntest" 51 | 52 | DEVICE_BUS = 1 # Define I2C bus 53 | DEVICE_ADDR = 0x17 # Define device i2c slave address. 54 | 55 | MQTT_TOPIC_FAN = "/fanspeed" 56 | MQTT_TOPIC_UPS = "/ups" 57 | MQTT_TOPIC_LWT = "/LWT" 58 | MQTT_PAYLOAD_ONLINE = "online" 59 | MQTT_PAYLOAD_OFFLINE = "offline" 60 | 61 | 62 | def read_config_desired_cpu_temp(): 63 | global DESIRED_CPU_TEMP 64 | confparser = configparser.RawConfigParser() 65 | confparser.read(os.path.join(sys.path[0], CONFIG_FILE)) 66 | DESIRED_CPU_TEMP = int(confparser.get(CONFIGSECTION_FAN, "DESIRED_CPU_TEMP_degC")) 67 | 68 | 69 | def read_config(): 70 | global GPIO_FAN # The GPIO pin ID to control the fan 71 | global FAN_LOOP_TIME 72 | global FANSPEED_FILENAME 73 | global SEND_STATUS_TO_UPSPLUS_IOT_PLATFORM 74 | global UPSPLUS_IOT_PLATFORM_URL 75 | global INA219SHUNT_OUT 76 | global INA219SHUNT_BATT 77 | global BATT_LOOP_TIME 78 | global TIMER_BIAS_AT_STARTUP 79 | global one_hour_delay 80 | global SHUTDOWN_IMMEDIATELY_WHEN_ON_BATTERY # for testing shutdown only 81 | global SHUTDOWN_TIMEOUT 82 | global PROTECTION_VOLTAGE_MARGIN_mV 83 | global HIGH_BATT_TEMP 84 | global MQTT_BROKER 85 | global MQTT_PORT 86 | global MQTT_USERNAME 87 | global MQTT_PASSWORD 88 | global MQTT_TOPIC 89 | 90 | try: 91 | confparser = configparser.RawConfigParser() 92 | confparser.read(os.path.join(sys.path[0], CONFIG_FILE)) 93 | 94 | GPIO_FAN = int(confparser.get(CONFIGSECTION_FAN, "GPIO_FAN")) 95 | FAN_LOOP_TIME = int(confparser.get(CONFIGSECTION_FAN, "FAN_LOOP_TIME_s")) 96 | read_config_desired_cpu_temp() 97 | 98 | try: 99 | INA219SHUNT_OUT = float(confparser.get(CONFIGSECTION_UPS, "INA219_SHUNT_OUT_Ohm")) 100 | print(f"INA219 shunt for output current: {INA219SHUNT_OUT} Ohm") 101 | except Exception as exc: 102 | INA219SHUNT_OUT = 0.00725 # value provided by Geekpi 103 | try: 104 | INA219SHUNT_BATT = float(confparser.get(CONFIGSECTION_UPS, "INA219_SHUNT_BATT_Ohm")) 105 | print(f"INA219 shunt for battery current: {INA219SHUNT_BATT} Ohm") 106 | except Exception as exc: 107 | INA219SHUNT_BATT = 0.005 # value provided by Geekpi 108 | 109 | SEND_STATUS_TO_UPSPLUS_IOT_PLATFORM = 1 == int(confparser.get(CONFIGSECTION_UPS, "SEND_STATUS_TO_UPSPLUS_IOT_PLATFORM")) 110 | try: 111 | UPSPLUS_IOT_PLATFORM_URL = confparser.get(CONFIGSECTION_UPS, "UPSPLUS_IOT_PLATFORM_URL") 112 | except: 113 | UPSPLUS_IOT_PLATFORM_URL = "https://api.52pi.com/feed" 114 | 115 | BATT_LOOP_TIME = int(confparser.get(CONFIGSECTION_UPS, "BATTERY_CHECK_LOOP_TIME_s")) 116 | if CMD_NO_TIMER_BIAS in sys.argv: 117 | TIMER_BIAS_AT_STARTUP = 0 118 | one_hour_delay = 0 119 | print("Timer bias at start-up set to 0") 120 | else: 121 | try: 122 | TIMER_BIAS_AT_STARTUP = -int(confparser.get(CONFIGSECTION_UPS, "TIMER_BIAS_AT_STARTUP")) 123 | if TIMER_BIAS_AT_STARTUP == 0: 124 | one_hour_delay = 0 125 | except: 126 | TIMER_BIAS_AT_STARTUP = -300 + BATT_LOOP_TIME 127 | 128 | if CMD_SHUTDOWN_IMMEDIATELY_WHEN_ON_BATTERY in sys.argv: 129 | SHUTDOWN_IMMEDIATELY_WHEN_ON_BATTERY = True 130 | else: 131 | try: 132 | SHUTDOWN_IMMEDIATELY_WHEN_ON_BATTERY = (1 == int(confparser.get(CONFIGSECTION_UPS, "SHUTDOWN_IMMEDIATELY_WHEN_ON_BATTERY"))) 133 | except: 134 | SHUTDOWN_IMMEDIATELY_WHEN_ON_BATTERY = False 135 | if SHUTDOWN_IMMEDIATELY_WHEN_ON_BATTERY: 136 | print("Will immediately shut down when UPS is on battery.") 137 | SHUTDOWN_TIMEOUT = int(confparser.get(CONFIGSECTION_UPS, "SHUTDOWN_TIMEOUT_s")) 138 | 139 | parm = "PROTECTION_VOLTAGE_MARGIN_mV" 140 | PROTECTION_VOLTAGE_MARGIN_mV = int(confparser.get(CONFIGSECTION_UPS, parm)) 141 | protVmargin_mini_mV = 100 142 | protVmargin_maxi_mV = 500 143 | if PROTECTION_VOLTAGE_MARGIN_mV < protVmargin_mini_mV: 144 | print("{} set to {:.0f} mV".format(parm, protVmargin_mini_mV)) 145 | PROTECTION_VOLTAGE_MARGIN_mV = protVmargin_mini_mV 146 | if PROTECTION_VOLTAGE_MARGIN_mV > protVmargin_maxi_mV: 147 | print("{} set to {:.0f} mV".format(parm, protVmargin_maxi_mV)) 148 | PROTECTION_VOLTAGE_MARGIN_mV = protVmargin_maxi_mV 149 | 150 | try: 151 | HIGH_BATT_TEMP = int(confparser.get(CONFIGSECTION_UPS, "HIGH_BATT_TEMP")) 152 | except: 153 | HIGH_BATT_TEMP = 99 #disables warning about high battery temperature 154 | 155 | MQTT_BROKER = confparser.get(CONFIGSECTION_MQTT, "BROKER") 156 | MQTT_PORT = int(confparser.get(CONFIGSECTION_MQTT, "TCP_PORT")) 157 | MQTT_USERNAME = confparser.get(CONFIGSECTION_MQTT, "USERNAME") 158 | MQTT_PASSWORD = confparser.get(CONFIGSECTION_MQTT, "PASSWORD") 159 | MQTT_TOPIC = confparser.get(CONFIGSECTION_MQTT, "TOPIC") 160 | return True 161 | except Exception as e: 162 | errmsg = "Error when reading configuration parameters: " + str(e) 163 | print(errmsg) 164 | syslog.syslog(syslog.LOG_ERR, errmsg) 165 | return False 166 | 167 | 168 | def on_MQTTconnect(client, userdata, flags, rc): 169 | client.connection_rc = rc 170 | if rc == 0: 171 | client.connected_flag = True 172 | msg = "Connected to MQTT broker" 173 | print(msg) 174 | syslog.syslog(syslog.LOG_INFO, msg) 175 | try: 176 | client.publish(MQTT_TOPIC + MQTT_TOPIC_LWT, MQTT_PAYLOAD_ONLINE, 0, retain=True) 177 | except: 178 | pass 179 | else: 180 | errMsg = { 181 | 1: "Connection refused – incorrect protocol version", 182 | 2: "Connection refused – invalid client identifier", 183 | 3: "Connection refused – server unavailable", 184 | 4: "Connection refused – bad username or password", 185 | 5: "connection not autorized" 186 | } 187 | errMsgFull = "Connection to MQTT broker failed. " + errMsg.get(rc, f"Unknown error: {str(rc)}.") 188 | print(errMsgFull) 189 | syslog.syslog(syslog.LOG_ERR, errMsgFull) 190 | 191 | def on_MQTTdisconnect(client, userdata, rc): 192 | # print("disconnecting reason " + str(rc)) 193 | client.connected_flag = False 194 | 195 | def MQTT_connect(client): 196 | # returns True if we started the connection loop, False otherwise 197 | # the connection loop will take care of reconnections 198 | client.on_connect = on_MQTTconnect 199 | client.on_disconnect = on_MQTTdisconnect 200 | client.will_set(MQTT_TOPIC + MQTT_TOPIC_LWT, MQTT_PAYLOAD_OFFLINE, 0, retain=True) 201 | if len(MQTT_USERNAME) > 0: 202 | client.username_pw_set(username=MQTT_USERNAME, password=MQTT_PASSWORD) 203 | # print("Connecting to broker ",MQTT_BROKER) 204 | try: 205 | client.connect(MQTT_BROKER, MQTT_PORT) #connect to broker 206 | client.loop_start() 207 | except Exception as e: 208 | errMsg = f"MQTT connection attempt failed: {e}. Will be retried." 209 | print(errMsg) 210 | syslog.syslog(syslog.LOG_WARNING, errMsg) 211 | return False 212 | timeout = time.time() + 5 213 | while client.connection_rc == -1: #wait in loop 214 | if time.time() > timeout: 215 | break 216 | time.sleep(1) 217 | # print("MQTT wait...") 218 | return True 219 | 220 | def MQTT_terminate(client): 221 | try: 222 | if client.connected_flag: 223 | res = MQTT_client.publish(MQTT_TOPIC + MQTT_TOPIC_LWT, MQTT_PAYLOAD_OFFLINE, 0, retain=True) 224 | # if res[0] == 0: 225 | # print("mqtt go offline ok") 226 | MQTT_client.disconnect() 227 | sleep(1) 228 | client.loop_stop() 229 | except Exception as e: 230 | print("MQTT client terminated with exception: " + str(e)) 231 | pass 232 | 233 | def i2c_bus_read_byte_wait(devaddr, reg, delay_s): 234 | sleep(delay_s) 235 | return i2c_bus.read_byte_data(devaddr, reg) 236 | 237 | class UPSPlus: 238 | def __init__(self, upsCurrent, upsHealthCheck): 239 | self._send_status_data_reply = "" 240 | # get battery status 241 | try: 242 | self._battery_voltage_V = inaBattery.voltage() 243 | try: 244 | self._battery_current_mA = -inaBattery.current() # positive: discharge current 245 | except DeviceRangeError: 246 | self._battery_current_mA = 16000 247 | except Exception as exc: 248 | raise Exception("[UPSPLus.init] Error reading inaBatt registers: " + str(exc)) 249 | self._battery_current_avg_mA = upsCurrent.battery_current_avg_mA 250 | self._battery_power_avg_mW = upsCurrent.battery_power_avg_mW 251 | # get output status 252 | try: 253 | self._RPi_voltage_V = inaRPi.voltage() 254 | try: 255 | self._RPi_current_mA = inaRPi.current() 256 | except DeviceRangeError: 257 | self._RPi_current_mA = 16000 258 | except Exception as exc: 259 | raise Exception("[UPSPLus.init] Error reading inaRPi registers: " + str(exc)) 260 | self._RPi_current_avg_mA = upsCurrent.out_current_avg_mA 261 | self._RPi_power_avg_mW = upsCurrent.out_power_avg_mW 262 | self._RPi_current_peak_mA = upsCurrent.out_current_peak_mA 263 | self._RPi_voltage_mini_V = upsCurrent.out_voltage_mini_V 264 | 265 | # we only read the full set of registers if we report back to the IOT Platform 266 | # otherwise just read the register values we actually use 267 | if SEND_STATUS_TO_UPSPLUS_IOT_PLATFORM: 268 | it_registers = it.chain(range(0x01,0x2A), range(0xF0,0xFC)) 269 | else: 270 | it_registers = it.chain(range(0x07,0x0C), range(0x11, 0x15)) 271 | try: 272 | # pick one of the following lines (with or without delay) 273 | # self._reg_buff = {i:i2c_bus.read_byte_data(DEVICE_ADDR, i) for i in it_registers} 274 | self._reg_buff = {i:i2c_bus_read_byte_wait(DEVICE_ADDR, i, 0.02) for i in it_registers} 275 | except Exception as exc: 276 | raise Exception("[UPSPLus.init] Error reading UPS registers: " + str(exc)) 277 | 278 | self._USB_C_mV = self._reg_buff[0x08] << 8 | self._reg_buff[0x07] 279 | self._USB_micro_mV = self._reg_buff[0x0A] << 8 | self._reg_buff[0x09] 280 | # self.battery_temperature_degC = self.reg_buff[12] << 8 | self.reg_buff[11] 281 | # we very rarely get 0xFF at reg_buff[0x0C]. this value should be 0 anyway for realistic temperatures 282 | BATT_TEMP_CEILING = 70 # sometimes unrealistic values spoil my graphs 283 | self._battery_temperature_degC = min(self._reg_buff[0x0B], BATT_TEMP_CEILING) 284 | upsHealthCheck.check_batt_temperature(self._battery_temperature_degC) 285 | upsHealthCheck.check_charger(self.on_battery, self._battery_current_avg_mA) 286 | # self._battery_remaining_capacity_percent = self._reg_buff[0x14] << 8 | self._reg_buff[0x13] 287 | # remaining capacity always <= 100% 288 | BATT_CAPACITY_CEILING = 101 289 | self._battery_remaining_capacity_percent = min(self._reg_buff[0x13], BATT_CAPACITY_CEILING) 290 | self._healthy = upsHealthCheck.is_healthy 291 | 292 | @property 293 | def protection_voltage_mV(self): 294 | prot_voltage_mV = self._reg_buff[0x12] << 8 | self._reg_buff[0x11] 295 | # protection voltage should be between 3000 and (4000 - margin) mV. 296 | # the UPS firmware is supposed to shut down RPi power when battery voltage goes lower than the Battery Protection Voltage. 297 | # so we have to make sure to gracefully shut down the RPi before we reach this level. 298 | # the script will shut down the RPi at Battery Protection Voltage + _Margin (config. parameter). 299 | # Battery Protection Voltage checks: 300 | # lower bound: make sure that the script will shut down the RPi when battery voltage comes close to the 3000 mV limit. 301 | # Below such battery voltage the charger circuit (IP5328) will go into low current charge mode, 302 | # and charging current won't be sufficient to power the RPi. 303 | # upper bound: make sure the script will not shut down the RPi with a (nearly) full battery 304 | if prot_voltage_mV >= 3000 and prot_voltage_mV <= (4000 - PROTECTION_VOLTAGE_MARGIN_mV) : 305 | pass 306 | else: 307 | PROTECT_VOLT_DEFAULT_mV = 3500 308 | errMsg = f"Protection voltage retrieved from UPS seems to have an incorrect value ({prot_voltage_mV:.0f} mV). "\ 309 | f"Assumed to be {PROTECT_VOLT_DEFAULT_mV:.0f} mV" 310 | print(errMsg) 311 | syslog.syslog(syslog.LOG_WARNING, errMsg) 312 | prot_voltage_mV = PROTECT_VOLT_DEFAULT_mV 313 | return prot_voltage_mV 314 | 315 | @property 316 | def on_battery(self): 317 | # with previous firmwares (earlier than v. 10) it seemed more reliable to check discharging current. 318 | # with firmware >= v.10 we go back to checking the USB ports 319 | # USB-C and micro-USB voltages are sometimes not reported properly 320 | # return self._battery_current_avg_mA > 500 # positive current means battery is discharging 321 | return (self._USB_C_mV < 4000) and (self._USB_micro_mV < 4000) 322 | 323 | @property 324 | def battery_is_charging(self): 325 | return self._battery_current_avg_mA < 0 326 | 327 | @property 328 | def battery_voltage_V(self): 329 | return self._battery_voltage_V 330 | 331 | def MQTT_publish(self, mqttclient): 332 | dictPayload = { 333 | 'UsbC_V': self._USB_C_mV / 1000, 334 | 'UsbMicro_V': self._USB_micro_mV / 1000, 335 | 'OnBattery': self.on_battery, 336 | 'BatteryVoltage_V': self._battery_voltage_V, 337 | 'BatteryCurrent_A': int(self._battery_current_mA) / 1000., 338 | 'BatteryCurrent_avg_A': int(self._battery_current_avg_mA) / 1000., 339 | 'BatteryPower_avg_W': int(self._battery_power_avg_mW)/1000., 340 | 'BatteryCharging': self.battery_is_charging, 341 | 'BatteryRemainingCapacity_percent': self._battery_remaining_capacity_percent, 342 | 'BatteryTemperature_degC': self._battery_temperature_degC, 343 | 'OutputVoltage_V': self._RPi_voltage_V, 344 | 'OutputVoltage_mini_V': self._RPi_voltage_mini_V, 345 | 'OutputCurrent_A': int(self._RPi_current_mA) / 1000., 346 | 'OutputCurrent_avg_A': int(self._RPi_current_avg_mA) / 1000., 347 | 'OutputPower_avg_W': int(self._RPi_power_avg_mW) / 1000., 348 | 'OutputCurrent_peak_A': int(self._RPi_current_peak_mA) / 1000., 349 | 'IsHealthy': self._healthy, 350 | } 351 | if SEND_STATUS_TO_UPSPLUS_IOT_PLATFORM: 352 | dictPayload['UPSPlus_IOT_Platform_Reply'] = self._send_status_data_reply 353 | payload = json.dumps(dictPayload) 354 | try: 355 | res = mqttclient.publish(MQTT_TOPIC + MQTT_TOPIC_UPS, payload, 0, False) 356 | except: 357 | pass 358 | # if res[0] == 0: 359 | # print("publish successful: " + payload) 360 | # else: 361 | # print("public failed. result: " + str(res.result)) 362 | 363 | def send_UPS_status_data(self): 364 | global send_status_data_warncount 365 | # time.sleep(random.randint(0, 3)) 366 | tel_data = { 367 | 'PiVccVolt': self._RPi_voltage_V, 368 | 'PiIddAmps': self._RPi_current_mA, 369 | 'BatVccVolt': self._battery_voltage_V, 370 | 'BatIddAmps': -self._battery_current_mA, 371 | 'McuVccVolt': self._reg_buff[2] << 8 | self._reg_buff[1], 372 | 'BatPinCVolt': self._reg_buff[6] << 8 | self._reg_buff[5], 373 | 'ChargeTypeCVolt': self._reg_buff[8] << 8 | self._reg_buff[7], 374 | 'ChargeMicroVolt': self._reg_buff[10] << 8 | self._reg_buff[9], 375 | 'BatTemperature': self._reg_buff[12] << 8 | self._reg_buff[11], 376 | 'BatFullVolt': self._reg_buff[14] << 8 | self._reg_buff[13], 377 | 'BatEmptyVolt': self._reg_buff[16] << 8 | self._reg_buff[15], 378 | 'BatProtectVolt': self._reg_buff[18] << 8 | self._reg_buff[17], 379 | 'SampleTime': self._reg_buff[22] << 8 | self._reg_buff[21], 380 | 'AutoPowerOn': self._reg_buff[25], 381 | 'OnlineTime': (self._reg_buff[31] << 24 | self._reg_buff[30] << 16 382 | | self._reg_buff[29] << 8 | self._reg_buff[28]), 383 | 'FullTime': (self._reg_buff[35] << 24 | self._reg_buff[34] << 16 384 | | self._reg_buff[33] << 8 | self._reg_buff[32]), 385 | 'OneshotTime': (self._reg_buff[39] << 24 | self._reg_buff[38] << 16 386 | | self._reg_buff[37] << 8 | self._reg_buff[36]), 387 | 'Version': self._reg_buff[41] << 8 | self._reg_buff[40], 388 | 'UID0': "%08X" % (self._reg_buff[243] << 24 | self._reg_buff[242] << 16 389 | | self._reg_buff[241] << 8 | self._reg_buff[240]), 390 | 'UID1': "%08X" % (self._reg_buff[247] << 24 | self._reg_buff[246] << 16 391 | | self._reg_buff[245] << 8 | self._reg_buff[244]), 392 | 'UID2': "%08X" % (self._reg_buff[251] << 24 | self._reg_buff[250] << 16 393 | | self._reg_buff[249] << 8 | self._reg_buff[248]), 394 | } 395 | # print(tel_data) 396 | try: 397 | r = requests.post(UPSPLUS_IOT_PLATFORM_URL, data=tel_data) 398 | # print(r.text) 399 | # json data will be formatted with double quotes, so replace them 400 | self._send_status_data_reply = r.text.replace('"', "'") 401 | send_status_data_warncount = 0 402 | except Exception as e: 403 | # print("sending UPS status data failed: " + str(e)) 404 | warncount = 10 405 | self._send_status_data_reply = "sending UPS status data failed: " + str(e) 406 | if send_status_data_warncount == warncount: 407 | errmsg = f"sending UPS status data failed {warncount} times: " + str(e) 408 | syslog.syslog(syslog.LOG_ERR, errmsg) 409 | print(errmsg) 410 | if send_status_data_warncount <= warncount: 411 | send_status_data_warncount += 1 412 | 413 | 414 | class UPSVoltageCurrent: 415 | 416 | def __init__(self): 417 | self._batt_current = deque([]) 418 | self._batt_power = deque([]) 419 | self._out_current = deque([]) 420 | self._out_power = deque([]) 421 | self._min_RPi_voltage = 6 422 | self._max_out_current = 0 423 | self._can_warn = 0 424 | self._arrLength = 2 * BATT_LOOP_TIME 425 | 426 | def add_value(self): 427 | had_warning = False 428 | had_exception = False 429 | # get measurements and handle i2c bus exceptions 430 | try: 431 | battcurr = -inaBattery.current() 432 | battvolt = inaBattery.voltage() 433 | except Exception as exc: 434 | had_exception = True 435 | if self._can_warn == 0: 436 | syslog.syslog(syslog.LOG_ERR, "[C_UpsCurrent.add_value] Error reading inaBatt registers: " + str(exc)) 437 | had_warning = True 438 | try: 439 | outcurr = inaRPi.current() 440 | outvolt = inaRPi.voltage() 441 | except Exception as exc: 442 | had_exception = True 443 | if self._can_warn == 0: 444 | syslog.syslog(syslog.LOG_ERR, "[C_UpsCurrent.add_value] Error reading inaRPi registers: " + str(exc)) 445 | had_warning = True 446 | # in case we get repeated errors on the i2c bus, we make sure we do not get a warning about this every second 447 | if had_warning: 448 | self._can_warn = 60 # send a warning once a minute at most 449 | else: 450 | if self._can_warn > 0: 451 | self._can_warn -= 1 452 | if had_exception: 453 | return 454 | # put measures into arrays 455 | if len(self._batt_current) >= self._arrLength: 456 | self._batt_current.popleft() 457 | self._batt_current.append(battcurr) 458 | if len(self._batt_power) >= self._arrLength: 459 | self._batt_power.popleft() 460 | self._batt_power.append(battcurr * battvolt) # we do not use the ina.power() function as it always returns positive 461 | if len(self._out_current) >= self._arrLength: 462 | self._out_current.popleft() 463 | self._out_current.append(outcurr) 464 | if self._max_out_current < outcurr: 465 | self._max_out_current = outcurr 466 | if len(self._out_power) >= self._arrLength: 467 | self._out_power.popleft() 468 | self._out_power.append(outcurr * outvolt) 469 | if outvolt < self._min_RPi_voltage: 470 | self._min_RPi_voltage = outvolt 471 | 472 | @property 473 | def battery_current_avg_mA(self): 474 | if len(self._batt_current) > 0: 475 | return sum(self._batt_current) / len(self._batt_current) 476 | else: 477 | return 0 478 | 479 | @property 480 | def battery_power_avg_mW(self): 481 | if len(self._batt_power) > 0: 482 | return sum(self._batt_power) / len(self._batt_power) 483 | else: 484 | return 0 485 | 486 | @property 487 | def out_current_avg_mA(self): 488 | if len(self._out_current) > 0: 489 | return sum(self._out_current) / len(self._out_current) 490 | else: 491 | return 0 492 | 493 | @property 494 | def out_power_avg_mW(self): 495 | if len(self._out_power) > 0: 496 | return sum(self._out_power) / len(self._out_power) 497 | else: 498 | return 0 499 | 500 | @property 501 | # Getting the value will reset max value !!! 502 | def out_current_peak_mA(self): 503 | tmpMax = self._max_out_current 504 | self._max_out_current = 0 505 | return tmpMax 506 | 507 | @property 508 | # Getting the value will reset max value !!! 509 | def out_voltage_mini_V(self): 510 | tmpMin = self._min_RPi_voltage 511 | self._min_RPi_voltage = 6 512 | return tmpMin 513 | 514 | 515 | class UPSHealth: 516 | # the UPS is considered unhealthy if... 517 | # - more than 9 consecutive battery temperature readings are equal. 518 | # this occurred frequently with firmware versions <= 9) but has not been observed so far for v.10. 519 | # when this occurred, the UPS would not perform the shutdown procedure at the end of battery life, and would not switch off power to the RPi. 520 | # - at least 3 consecutive battery temperature readings are over threshold 521 | # - charging circuit works properly: the battery is not discharging when not on battery 522 | def __init__(self, high_batt_temp): 523 | self._lastTemp = -1 524 | self._UNHEALTHY_EQUAL_BATT_TEMP_VALUES_COUNT = 20 525 | self._equalValuesFound = 0 526 | self._HIGH_BATT_TEMP = high_batt_temp 527 | self._highBattTempValuesFound = 0 528 | self._HIGH_BATT_TEMP_MAXCOUNT = 3 529 | self._charger_works_properly = True 530 | self._batt_current = deque([]) 531 | self._arrLength = 5 532 | self._ignore_next_batt_current = False 533 | 534 | def check_batt_temperature(self, batt_temp): 535 | if batt_temp == self._lastTemp: 536 | if self._equalValuesFound <= self._UNHEALTHY_EQUAL_BATT_TEMP_VALUES_COUNT: 537 | self._equalValuesFound += 1 538 | else: 539 | self._lastTemp = batt_temp 540 | self._equalValuesFound = 0 541 | if batt_temp > self._HIGH_BATT_TEMP: 542 | if self._highBattTempValuesFound <= self._HIGH_BATT_TEMP_MAXCOUNT: 543 | self._highBattTempValuesFound += 1 544 | else: 545 | self._highBattTempValuesFound = 0 546 | 547 | def check_charger(self, ups_on_battery, avg_batt_current_mA): 548 | # do not try to detect charger malfunction when UPS is on battery 549 | # do not take first reading after on_battery disappears, because avg current may still be positive at first 550 | if ups_on_battery or self._ignore_next_batt_current: 551 | if len(self._batt_current) > 0: 552 | self._batt_current.clear() 553 | self._ignore_next_batt_current = False 554 | else: 555 | if len(self._batt_current) >= self._arrLength: 556 | self._batt_current.popleft() 557 | self._batt_current.append(avg_batt_current_mA) 558 | if ups_on_battery: 559 | self._ignore_next_batt_current = True 560 | # we make another average of avg batt current readings to get rid of current spikes 561 | # due to battery voltage probings 562 | avg_avg_batt_current_mA = 0 563 | if len(self._batt_current) == self._arrLength: 564 | avg_avg_batt_current_mA = sum(self._batt_current) / len(self._batt_current) 565 | self._charger_works_properly = not (not ups_on_battery and (avg_avg_batt_current_mA > 100 )) 566 | # print(f"avg batt current: {avg_batt_current_mA}, avg avg batt current: {avg_avg_batt_current_mA}") 567 | # we take 0.1A as a limit to stay clear of battery discharge current due to battery voltage probing 568 | 569 | @property 570 | def is_healthy(self): 571 | errMsg = "" 572 | if not (self._equalValuesFound < self._UNHEALTHY_EQUAL_BATT_TEMP_VALUES_COUNT): 573 | errMsg = "[UPS health] Got too many identical battery temperature values" 574 | if not (self._highBattTempValuesFound < self._HIGH_BATT_TEMP_MAXCOUNT): 575 | errMsg = "[UPS health] Battery temperature seems too high" 576 | if not self._charger_works_properly: 577 | errMsg = "[UPS health] Charger connected, but battery is discharging" 578 | if len(errMsg) > 0: 579 | print(errMsg) 580 | syslog.syslog(syslog.LOG_ERR, errMsg) 581 | 582 | return (self._equalValuesFound < self._UNHEALTHY_EQUAL_BATT_TEMP_VALUES_COUNT) \ 583 | and (self._highBattTempValuesFound < self._HIGH_BATT_TEMP_MAXCOUNT) \ 584 | and self._charger_works_properly 585 | 586 | 587 | class Fan: 588 | def __init__(self, mqttclient): 589 | self._currentfanspeed = 999 590 | self._speed = 100 591 | self._fansum = 0 592 | self._pTemp = 15 593 | self._iTemp = 0.4 594 | GPIO.setmode(GPIO.BCM) 595 | GPIO.setwarnings(False) 596 | GPIO.setup(GPIO_FAN, GPIO.OUT) 597 | self._myPWM = GPIO.PWM(GPIO_FAN, 50) 598 | self._myPWM.start(50) 599 | self._mqttclient = mqttclient 600 | self.switch_off() 601 | 602 | def set_speed(self): 603 | def get_CPU_temperature(): 604 | res = os.popen('vcgencmd measure_temp').readline() 605 | temp =(res.replace("temp=","").replace("'C\n","")) 606 | # print("temp is {0}".format(temp)) #Uncomment here for testing 607 | return temp 608 | try: 609 | actualTemp = float(get_CPU_temperature()) 610 | except Exception as exc: 611 | print("[get_cpu_temperature] exception: " + str(exc)) 612 | return 613 | diff = actualTemp - DESIRED_CPU_TEMP 614 | self._fansum = self._fansum + diff 615 | pDiff = diff * self._pTemp 616 | iDiff = self._fansum * self._iTemp 617 | self._speed = pDiff + iDiff 618 | if self._speed > 100: 619 | self._speed = 100 620 | if self._speed < 15: 621 | self._speed = 0 622 | if self._fansum > 100: 623 | self._fansum = 100 624 | if self._fansum < -100: 625 | self._fansum = -100 626 | self._myPWM.ChangeDutyCycle(self._speed) 627 | self._publish_speed() 628 | 629 | def switch_off(self): 630 | self._myPWM.ChangeDutyCycle(0) # switch fan off 631 | self._speed = 0 632 | self._publish_speed() 633 | return 634 | 635 | def _publish_speed(self): 636 | if self._mqttclient.connected_flag and (self._speed != self._currentfanspeed): 637 | try: 638 | res = self._mqttclient.publish(MQTT_TOPIC + MQTT_TOPIC_FAN, str(int(self._speed)), 0, True) 639 | if res[0] == 0: 640 | self._currentfanspeed = self._speed 641 | except Exception as e: 642 | pass 643 | return 644 | 645 | def cleanup(self): 646 | self.switch_off() 647 | GPIO.cleanup() # resets all GPIO ports used by this program 648 | 649 | had_upsplus_exception = False 650 | 651 | def get_UPS_status_and_check_battery_voltage(mqttclient): 652 | global UPS_was_on_battery, had_upsplus_exception, one_hour_delay 653 | try: 654 | upsplus = UPSPlus(UPS_voltage_current, UPS_health_check) 655 | had_upsplus_exception = False 656 | except Exception as exc: 657 | # only log error if 2 or more exceptions without interruption 658 | if had_upsplus_exception: 659 | errMsg = "[get_UPS_status_and_check_battery_voltage] Error getting data from UPS: " + str(exc) 660 | print(errMsg) 661 | syslog.syslog(syslog.LOG_ERR, errMsg) 662 | else: 663 | had_upsplus_exception = True 664 | return 665 | if SEND_STATUS_TO_UPSPLUS_IOT_PLATFORM: 666 | upsplus.send_UPS_status_data() 667 | try: 668 | if mqttclient.connected_flag: 669 | upsplus.MQTT_publish(mqttclient) 670 | except Exception as e: 671 | print("mqttpublish exception: " + str(e)) 672 | pass 673 | 674 | if upsplus.on_battery: 675 | UPS_was_on_battery = True 676 | else: 677 | if UPS_was_on_battery: 678 | syslog.syslog(syslog.LOG_INFO, 'UPS back on AC supply.') 679 | UPS_was_on_battery = False 680 | 681 | if upsplus.on_battery or (one_hour_delay == 0): 682 | shutdown_at_battvoltage_V = (upsplus.protection_voltage_mV + PROTECTION_VOLTAGE_MARGIN_mV) / 1000 683 | if upsplus.on_battery: 684 | syslog.syslog(syslog.LOG_WARNING, 685 | f"UPS on battery. Battery voltage: {upsplus.battery_voltage_V:.3f} V. " 686 | f"Shutdown at {shutdown_at_battvoltage_V:.3f} V") 687 | if upsplus._battery_voltage_V > 1: # protect against bad battery voltage reading 688 | if upsplus._battery_voltage_V < shutdown_at_battvoltage_V : 689 | syslog.syslog(syslog.LOG_WARNING, 690 | f"UPS battery voltage below threshold of {shutdown_at_battvoltage_V:.3f} V. Shutting down.") 691 | if not upsplus.on_battery: 692 | syslog.syslog(syslog.LOG_ERR, 693 | f"Low battery voltage may be caused by faulty charging circuit. Charger voltage present at USB input.") 694 | shut_down_RPi(mqttclient) 695 | else: 696 | if SHUTDOWN_IMMEDIATELY_WHEN_ON_BATTERY and upsplus.on_battery: 697 | syslog.syslog(syslog.LOG_INFO, 'Immediate shutdown.') 698 | shut_down_RPi(mqttclient) 699 | return 700 | 701 | 702 | def shut_down_RPi(mqttclient): 703 | if control_fan: 704 | fan.switch_off() 705 | MQTT_terminate(mqttclient) 706 | # initialize shutdown sequence. 707 | try: 708 | # enable switch on when back on AC 709 | i2c_bus.write_byte_data(DEVICE_ADDR, 0x19, 1) 710 | except Exception as exc: 711 | syslog.syslog(syslog.LOG_ERR, "[shut_down_RPi] Error writing UPS register (back to AC power up): " + str(exc)) 712 | try: 713 | i2c_bus.write_byte_data(DEVICE_ADDR, 0x18, SHUTDOWN_TIMEOUT) 714 | except Exception as exc: 715 | syslog.syslog(syslog.LOG_ERR, "[shut_down_RPi] Error writing UPS register (shutdown timeout): " + str(exc)) 716 | time.sleep(1) 717 | # os.system("sudo shutdown -h 1") 718 | os.system("sudo sync && sudo halt") 719 | while True: 720 | time.sleep(100) 721 | 722 | 723 | def UPS_is_present(): 724 | """ 725 | check if i2c bus is usable. check if we can read UPS registers. 726 | initialize i2c bus and both INA sensors 727 | returns False if we get an exception in any of these operations 728 | """ 729 | global i2c_bus 730 | global inaRPi 731 | global inaBattery 732 | 733 | # init i2c protocol 734 | try: 735 | i2c_bus = smbus2.SMBus(DEVICE_BUS) 736 | except Exception as e: 737 | errMsg = 'i2c bus for communication with UPS could not be initialized. Error message: ' + str(e) 738 | syslog.syslog(syslog.LOG_WARNING, errMsg) 739 | print(errMsg) 740 | return False 741 | # check if we can read UPS registers on the i2c bus 742 | try: 743 | void = i2c_bus.read_byte_data(DEVICE_ADDR, 0x12) 744 | except OSError as e: 745 | errMsg = 'No reply from UPS on i2c bus. Error message: ' + str(e) 746 | syslog.syslog(syslog.LOG_WARNING, errMsg) 747 | print(errMsg) 748 | return False 749 | # Raspberry Pi output current and voltage 750 | try: 751 | inaRPi = INA219(INA219SHUNT_OUT, busnum=DEVICE_BUS, address=0x40) 752 | inaRPi.configure(inaRPi.RANGE_32V, inaRPi.GAIN_AUTO, inaRPi.ADC_12BIT, inaRPi.ADC_12BIT) 753 | except Exception as exc: 754 | errMsg = 'Cannot initialize communication with INA219 (output). Error message: ' + str(exc) 755 | syslog.syslog(syslog.LOG_WARNING, errMsg) 756 | print(errMsg) 757 | return False 758 | # Battery current and voltage 759 | try: 760 | inaBattery = INA219(INA219SHUNT_BATT, busnum=DEVICE_BUS, address=0x45) 761 | inaBattery.configure(inaBattery.RANGE_32V, inaBattery.GAIN_AUTO, inaBattery.ADC_12BIT, inaBattery.ADC_12BIT) 762 | except Exception as exc: 763 | errMsg = 'Cannot initialize communication with INA219 (battery). Error message: ' + str(exc) 764 | syslog.syslog(syslog.LOG_WARNING, errMsg) 765 | print(errMsg) 766 | return False 767 | return True 768 | 769 | 770 | send_status_data_warncount = 0 771 | try: 772 | print(f"UPS-Plus to MQTT version {SCRIPT_VERSION}") 773 | print("Copyright (C) 2021 https://github.com/frtz13") 774 | print("This program comes with ABSOLUTELY NO WARRANTY") 775 | print("This is free software, and you are welcome to redistribute it") 776 | print("under conditions of the GPL (see http://www.gnu.org/licenses for details).") 777 | print() 778 | 779 | if not read_config(): 780 | print("Please check configuration file and parameters") 781 | syslog.syslog(syslog.LOG_WARNING, "Program stopped. Please check configuration file and parameters.") 782 | exit() 783 | 784 | print("Type ctrl-C to exit") 785 | syslog.syslog(syslog.LOG_INFO, f"Version {SCRIPT_VERSION} running...") 786 | 787 | # init MQTT connection 788 | connect_to_MQTT = MQTT_BROKER != "" 789 | mqtt.Client.connected_flag = False # create flags in class 790 | mqtt.Client.connection_rc = -1 791 | MQTT_client = mqtt.Client("fanShutDownUps") 792 | 793 | control_fan = (GPIO_FAN >= 0) 794 | if control_fan: 795 | try: 796 | fan = Fan(MQTT_client) 797 | except Exception as exc: 798 | errMsg = 'Fan class initialization failed. Error message: ' + str(exc) 799 | syslog.syslog(syslog.LOG_ERR, errMsg) 800 | print(errMsg) 801 | control_fan = False 802 | 803 | UPS_present = UPS_is_present() 804 | if UPS_present: 805 | UPS_voltage_current = UPSVoltageCurrent() 806 | UPS_health_check = UPSHealth(HIGH_BATT_TEMP) 807 | 808 | UPS_was_on_battery = False 809 | one_hour_delay = 3600 810 | 811 | # set negative value (-300 + BATT_LOOP_TIME) to force long waiting at startup. 812 | # so the RPi will be running for some minimum time if power fails again. 813 | # also, script won't shut down the RPi before elapse of this time, so we have a chance to kill the script should anything malfunction. 814 | # also allows to wait for the MQTT broker to start if it is running on the RPi, too. 815 | batterycheck_timer = TIMER_BIAS_AT_STARTUP 816 | 817 | fan_timer = 0 818 | MQTT_connection_loop_running = False 819 | if connect_to_MQTT: 820 | MQTT_connection_loop_running = MQTT_connect(MQTT_client) 821 | 822 | while True: 823 | if UPS_present: 824 | UPS_voltage_current.add_value() 825 | if control_fan: 826 | if fan_timer >= FAN_LOOP_TIME: 827 | fan_timer = 0 828 | fan.set_speed() 829 | else: 830 | fan_timer += 1 831 | if batterycheck_timer >= BATT_LOOP_TIME: 832 | batterycheck_timer = 0 833 | if connect_to_MQTT and not MQTT_connection_loop_running: 834 | MQTT_connection_loop_running = MQTT_connect(MQTT_client) 835 | if control_fan: 836 | read_config_desired_cpu_temp() 837 | if UPS_present: 838 | get_UPS_status_and_check_battery_voltage(MQTT_client) 839 | else: 840 | batterycheck_timer += 1 841 | if one_hour_delay > 0: 842 | one_hour_delay -= 1 843 | sleep(1) 844 | 845 | except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt 846 | if control_fan: 847 | fan.cleanup() 848 | MQTT_terminate(MQTT_client) 849 | print() 850 | syslog.syslog(syslog.LOG_INFO, "Stopped") 851 | 852 | --------------------------------------------------------------------------------