7
7
import json
8
8
import signal
9
9
import threading
10
+ import math
10
11
from datetime import datetime
11
12
import modbus_tk
12
13
import modbus_tk .defines as cst
@@ -31,6 +32,12 @@ def getenv():
31
32
'ec133' : {
32
33
'addr' : os .environ .get ('EC133_ADDR' , 1 ),
33
34
'timeout' : os .environ .get ('EC133_TIMEOUT' , 0.2 ),
35
+ 'linearization' : {
36
+ 'active' : bool (os .environ .get ('LINEARIZE' , True )),
37
+ 'range' : float (os .environ .get ('LINEARIZE_RANGE' , 255 )),
38
+ 'offset' : float (os .environ .get ('LINEARIZE_OFFSET' , 0.05 )),
39
+ 'tau' : float (os .environ .get ('LINEARIZE_TAU' , 0.55 ))
40
+ },
34
41
'command_topics' : {
35
42
'0' : os .environ .get ('CH0_COMMAND' , '' ),
36
43
'1' : os .environ .get ('CH1_COMMAND' , '' ),
@@ -103,6 +110,29 @@ def connect(self):
103
110
msg ("Unable to initialize RTU master" )
104
111
raise e
105
112
113
+ def _linearize (self ,ch ):
114
+
115
+ linconf = self .ecconf .get ('linearization' )
116
+
117
+ if linconf .get ('active' , False ) == False :
118
+ return
119
+
120
+ ch = int (ch )
121
+ new = self .register
122
+
123
+ if self .register [ch ] < 10 :
124
+ return
125
+
126
+ # f(x) = range*(1-offset)*exp(-(1-(x/range))/tau) + range*offset
127
+ exponent = (- 1 * ( 1 - ( float (new [ch ]) / linconf ['range' ]))) / linconf ['tau' ]
128
+ new [ch ] = int (linconf ['range' ]
129
+ * (1 - linconf ['offset' ])
130
+ * math .exp (exponent )
131
+ + (linconf ['range' ] * linconf ['offset' ])
132
+ )
133
+ msg ("Linearized as : %s" % str (new ))
134
+ self .register = new
135
+
106
136
def set_channel (self , client , userdata , message ):
107
137
108
138
ch = int (userdata ['channel' ])
@@ -125,13 +155,14 @@ def set_channel(self, client, userdata, message):
125
155
self .brightness [ch ] = int (payload ['brightness' ])
126
156
else :
127
157
payload ['brightness' ] = int (self .brightness [ch ])
128
- print (payload )
129
158
130
159
if payload .get ('state' , 'ON' ) == 'ON' :
131
160
self .register [ch ] = int (self .brightness [ch ])
132
161
else :
133
162
self .register [ch ] = int (0 )
134
163
164
+ self ._linearize (ch )
165
+
135
166
try :
136
167
self .rtu .execute (self .ecconf ['addr' ],
137
168
cst .WRITE_MULTIPLE_REGISTERS ,
0 commit comments