Check in
[owPython.git] / owlib.py
1 #!/usr/bin/python
2 # Copyright (c) 2017, Tobias Mueller tm(at)tm3d.de
3 # All rights reserved. 
4
5 # Redistribution and use in source and binary forms, with or without 
6 # modification, are permitted provided that the following conditions are 
7 # met: 
8
9 #  * Redistributions of source code must retain the above copyright 
10 #    notice, this list of conditions and the following disclaimer. 
11 #  * Redistributions in binary form must reproduce the above copyright 
12 #    notice, this list of conditions and the following disclaimer in the 
13 #    documentation and/or other materials provided with the 
14 #    distribution. 
15 #  * All advertising materials mentioning features or use of this 
16 #    software must display the following acknowledgement: This product 
17 #    includes software developed by tm3d.de and its contributors. 
18 #  * Neither the name of tm3d.de nor the names of its contributors may 
19 #    be used to endorse or promote products derived from this software 
20 #    without specific prior written permission. 
21
22 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
23 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
24 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
25 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
26 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
27 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
28 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
29 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
30 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
31 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
32 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
33
34
35
36
37 import time
38 import subprocess
39 import sys
40 devInfo= ["","temperature","pressure","illuminance","humidity","constant","voltage","current","VOC","counter","CO2","resistance"]
41 devUnit= ["","°C","hPa","lux","%","","V","mA","ppm","","ppm","kOhm"]
42
43 devController=["","Old code","Attiny84A","Attiny44","Atmega328"]
44
45 devChip=["","DS18B20","DS2438","DS2438","DS2438","DS2450","Thermoelement","SHT21","SHT25","DHT22","HIH9021","HDC1080","HIH4030","HIH5030","BMP280","MAX44009","CDM7160","MAX1164/TGS8100","TGS8100","DS2423"]
46
47
48 def calcValue(code,vn,V):
49         if code==0:
50                 return V[vn]
51         if code==1: 
52                 return V[vn] / 16.0; 
53         if code==2:
54                 return V[vn]/1.6; 
55         if code==3:
56                 return V[vn]*0.2 + 700; 
57         if code==4:
58                 return exp(V[vn] / 160.0); 
59         if code==5:
60                 return V[vn]*62.5 + 55000; 
61         if code==6:
62                 return V[vn] / 256.0; 
63         if code==7:
64                 return ((float(V[2]) / float(V[1]) - 0.16) / 0.0062) / (1.0546 - 0.00216*V[0]/256.0); 
65         if code==8:
66                 return V[vn] / 100.0; 
67         if code==9:
68                 return V[vn] / 65535.0*5.1; 
69         if code==10:
70                 return V[vn] / 65535.0*2.55;
71         if code==11:
72                 return V[vn] / 65535.0*1.1; 
73         if code==12:
74                 return V[vn] / 10.0; 
75         if code==13:
76                 return V[vn];  
77         if code==14:
78                 return (V[vn] - 32767.0) / 100.0;  
79         if code==15:
80                 return exp((V[vn]-32767.0)/1000.0);
81         if code==16:
82                 return V[vn]/32.0;  
83         return 0;
84
85
86
87 def owcom(dev,send,rc):
88         res=[]
89         try:
90                 f=open("/sys/bus/w1/devices/%s/rw" %(dev),"r+b",0)
91         except IOError:
92                 l=subprocess.check_output("rmmod w1_therm",shell=True)
93                 f=open("/sys/bus/w1/devices/%s/rw" %(dev),"r+b",0)
94         f.write("".join(map(chr, send)))
95         if (rc!=0):
96                 res=map(ord,f.read(rc))
97         f.close()
98         return res
99                 
100
101 def crc8(arr):
102         lscrc=0x0;
103         for v in arr:
104                 bit=1;
105                 while bit<256:
106                         if (v&bit)==bit:
107                                 lb=1
108                         else:
109                                 lb=0
110                         if (lscrc&1)!=lb:
111                                 lscrc=(lscrc>>1)^0x8c 
112                         else:
113                                 lscrc=(lscrc>>1)
114                         bit=bit*2
115         return (lscrc==0)
116
117
118 oddparity = [ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 ]
119
120
121 def crc16(arr):
122         crc16=0
123         for cdata in arr:
124                 cdata = (cdata ^ (crc16 & 0xff)) & 0xff;
125                 crc16 = crc16>>8;
126                 if (oddparity[cdata & 0xf] ^ oddparity[cdata >> 4]):
127                         crc16 = crc16 ^ 0xc001;
128                 cdata = (cdata << 6)&0xffff;
129                 crc16  = crc16 ^ cdata;
130                 cdata = (cdata << 1)&0xffff;
131                 crc16  = crc16^cdata;
132         #r=crc16==0xB001
133         return (crc16==0xB001)
134
135
136 def ow_fconvert(b1, b2):
137         tsht = b1 | (b2 << 8)
138         if (b2 & 0x080):
139                 tsht=-(tsht&0x7FFF)
140         return tsht
141
142         
143 def testnr(s):
144         for c in s.lower()[:]:
145                 if not((c) in ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','-']):
146                         return False
147         return True
148  
149 def addid(id,val):
150         for i in range(7):
151                 id[i+1]=id[i+1]+val
152                 if id[i+1]>254:
153                         id[i+1]=id[i+1]-254
154                         val=1
155                 else:
156                         return id
157         return id
158 #
159
160 def owfind(famcodes):
161         l=subprocess.check_output("ls /sys/bus/w1/devices/", shell=True)
162         dl=[]
163         for g in  (l.split("\n")):
164                 if len(g)>2:
165                         if testnr(g[0:2]):
166                                 if (g[0:2] in famcodes) or len(famcodes)==0:
167                                         dl.append(g)
168                         print g
169         return dl;
170
171
172 class owDevice:
173         raw=[0,0,0,0]
174         values=[0.0,0.0,0.0,0.0]
175         owid=""
176         config=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
177         def __init__(self, owid):
178                 self.owid = owid
179     
180         def setdefaultConfig(self):
181                 raise NotImplementedError()
182         
183         def readConfig(self):
184                 self.config=owcom(self.owid,[0x85],26)
185                 if self.config[0]==0xFF:
186                         print("No Deviceconfig. Not a Device form tm3d.de. Set Default");
187                         self.setdefaultConfig()
188                 else:
189                         if self.config[25]==0xFF:
190                                 if not(crc8(self.config[0:24])):
191                                         print("CRC Error reading Deviceconfig. Set Default")
192                                         self.setdefaultConfig()
193                         else:
194                                 if not(crc16([0x85]+self.config)):
195                                         print("CRC Error reading Deviceconfig. Set Default")
196                                         self.setdefaultConfig()
197
198         def convertAll(self):
199                 raise NotImplementedError()
200         
201         def getChips(self):
202                 l=[];
203                 for i in range(0,4):    
204                         l.append(devChip[self.config[i+9]])
205                 return l
206
207         def getUnits(self):
208                 l=[];
209                 for i in range(0,4):    
210                         l.append(devUnit[self.config[i*2]])
211                 return l
212
213         def getProperties(self):
214                 l=[];
215                 for i in range(0,4):    
216                         l.append(devInfo[self.config[i*2]])
217                 return l
218
219
220 class owDS2450(owDevice):
221         def setdefaultConfig(self):
222                 self.config=[6,9, 6,9, 6,9, 6,9, 0,5,5,5,5,0,0,0,0,0,0,0,0,0,0,0]
223         
224         def convertAll(self):
225                 ret=owcom(self.owid,[0x3C,0x0F,0x00],2)
226                 if not(crc16([0x3C,0x0F,0x00]+ret)):
227                         print("CRC ERROR")
228                         return
229                 time.sleep(1)
230                 ret=owcom(self.owid,[0xAA,0x00,0x00],10)
231                 if not(crc16([0xAA,0x00,0x00]+ret)):
232                         print("CRC ERROR")
233                         return
234                 for i in range(0,4):
235                         self.raw[i]=ret[2*i]|(ret[2*i+1]<<8);
236                 for i in range(0,4):    
237                         self.values[i]=calcValue(self.config[i*2+1],i,self.raw)
238                         
239         
240 class owDS18B20(owDevice):
241         def setdefaultConfig(self):
242                 self.config=[1,1, 0,0, 0,0, 0,0, 0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
243         
244         def convertAll(self):
245                 owcom(self.owid,[0x44],0)
246                 time.sleep(1)
247                 ret=owcom(self.owid,[0xBE],9)
248                 if not(crc8(ret)):
249                         print("CRC ERROR")
250                         return
251                 self.raw[0]=ow_fconvert(ret[0],ret[1]);
252                 self.values[0]=calcValue(self.config[0*2+1],0,self.raw)
253                 self.values[1]=0;
254                 self.values[2]=0;
255                 self.values[3]=0;
256
257 class owDS2438(owDevice):
258         def setdefaultConfig(self):
259                 self.config=[1,6, 6,8, 4,7, 7,17, 0,2,3,12,4,0,0,0,0,0,0,0,0,0,0,0]
260
261         def readScratchpad(self,page,recall):
262                 if (recall):
263                         owcom(self.owid,[0xB8,page],0)
264                 ret=owcom(self.owid,[0xBE,page],9)
265                 if not(crc8(ret)):
266                         print("CRC ERROR")
267                         return []
268                 return ret
269
270         def setConfigByte(self, cb):
271                 for i in range(3):
272                         owcom(self.owid,[0x4E,0x00,cb],0)
273                         sp=self.readScratchpad(0,False)
274                         if (sp!=[]):
275                                 if sp[0]==cb:
276                                         return True
277                 return False
278         
279
280                 
281         def convertAll(self):
282                 owcom(self.owid,[0x44],0)
283                 time.sleep(0.01)
284                 self.setConfigByte(0x08)
285                 owcom(self.owid,[0xB4],0)
286                 time.sleep(0.01)
287                 sp=self.readScratchpad(0,True)
288                 temp=ow_fconvert(sp[1],sp[2]);
289                 VDD=ow_fconvert(sp[3],sp[4]);
290                 self.setConfigByte(0x00)
291                 owcom(self.owid,[0xB4],0)
292                 time.sleep(0.01)
293                 sp=self.readScratchpad(0,True);
294                 I=ow_fconvert(sp[5],sp[6]);
295                 VAD=ow_fconvert(sp[3],sp[4]);
296                 self.raw[0]=temp;
297                 self.raw[1]=VDD;
298                 self.raw[2]=VAD;
299                 self.raw[3]=I;
300                 for i in range(0,4):    
301                         self.values[i]=calcValue(self.config[i*2+1],i,self.raw)
302
303 class owDS2423(owDevice):
304         def setdefaultConfig(self):
305                 self.config=[9,13, 9,13, 9,13, 9,13, 0,19,19,19,19,0,0,0,0,0,0,0,0,0,0,0]
306
307         def readCounter(self,page):
308                 addr=(page<<5)+31
309                 ret=owcom(self.owid,[0xA5,addr&0xFF,addr>>8],11)
310                 if not(crc16([0xA5,addr&0xFF,addr>>8]+ret)):
311                         print("CRC ERROR")
312                         return 0                
313                 c=0
314                 for i in range (4): 
315                         c<<=8;
316                         c|=ret[4-i];
317                 return c;
318         
319         
320         def convertAll(self):
321                 for i in range(4):
322                         self.raw[i]=self.readCounter(i+12);
323                 for i in range(0,4):    
324                         self.values[i]=calcValue(self.config[i*2+1],i,self.raw)
325