forked from matthewwall/weewx-wh23xx
-
Notifications
You must be signed in to change notification settings - Fork 1
/
wh23xx.py
1086 lines (948 loc) · 37.5 KB
/
wh23xx.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright 2016-2024 Matthew Wall
# Distributed under the terms of the GNU Public License (GPLv3)
#
# Thanks to Lloyd Kinsella
#
# 2024 Edwin Zuidema
# Modified and tested with Renkforce WH2315
"""
Collect data from Fine Offset WH23xx stations, including:
WH2300 (with RCC)
WH2301 (no RCC)
WH4000
Tycon TP2700
Renkforce WH2315
Based on the protocol specified in "TP2700 EEPROM data structure" V1.0 with
serial number FOS-ENG-022-A for model WH2300, and "TP2700 PC Protocol".
The console works with the all-in-one instrument cluster, or the separate
instruments.
The station includes a light sensor. The light sensor output is in lux, but
the station has a multiplicative lux-to-radiation conversion using a constant
in the station, which is factory set to 126.7. The station reports light in
lux, radiation in micro-W per square meter (labelled as UV), and UV index on
a scale of 1-15 (labelled as UVI).
The data logger in the console retains data through a power cycle.
Sensor specifications:
temperature: -40 to 60C
humidity: 1 to 99%
wind speed: 0 to 50 m/s
wind direction: 0 to 359 degree
rainfall: 0 to 9999.9 mm
light: 0 to 300000 lux
UV: 0 to 20000 uW/m^2
UVI: 0 to 15
pressure: 300-1100 hPa
===============================================================================
Current data include the following:
in temperature
out temperature
dewpoint
windchill
heatindex
in humidity
out humidity
abs pressure
rel pressure
wind direction
wind speed
gust speed
rain event
rain rate
rain hour
rain day
rain week
rain month
rain year
rain total
light
uv (radiation)
uv index
===============================================================================
Historical records include the following:
wind direction
wind speed
gust speed
rain total
in humidity
out humidity
in temperature
out temperature
pressure
light
uv (radiation)
The station has 3552 records. Each record is 18 bytes. The timestamp for each
record is stored separately from the record.
===============================================================================
Memory Map
0x0000 to 0x0258 : system, max/min, alarms, etc
0x0259 to 0x02c7 : 110 bytes : page flag structure
each byte is 0x01 to 0x20 or 0xff, indicating how many records in the page
0x02c8 to 0x063f : 110 8-byte segments : table structure (timestamps)
each 8-byte segment is a timestamp
year
month
day
hour
minute
second
interval (lsb)
interval (msb)
0x0640 to 0xffff : records
each record is 18 bytes
===============================================================================
Decoding current weather data
Temperature is value + 40C
Temperature, pressure, wind speed, rainfall, light are value / 10.0
Data are stored as hi byte first then lo byte
For 1 byte word, 0xff indicates invalid
For 2 byte word, 0xffff indicates invalid
For 4 byte word, 0xffffffff indicates invalid
The UVI is calculated from UV as follows:
UV UVI
UV_0 = 0
UV_1 = 99 0
UV_2 = 540 1
UV_3 = 1000 2
UV_4 = 1400 3
UV_5 = 1843 4
UV_6 = 2292 5
UV_7 = 2734 6
UV_8 = 3138 7
UV_9 = 3648 8
UV_10 = 4196 9
UV_11 = 4707 10
UV_12 = 5209 11
UV_13 = 5735 12
UV_14 = 6276 13
UV_15 = 6778 14
15
UV_MAX = 20000 0xff
===============================================================================
Commands
TIME_SYNC 0x01 [0x02 0x09]
READ_EEPROM 0x02 [0x02 0x05]
WRITE_EEPROM 0x03
READ_RECORD 0x04 [0x02 0x02]
READ_MAX 0x05 [0x02 0x02]
READ_MIN 0x06 [0x02 0x02]
READ_MAX_DAY 0x07 [0x02 0x02]
READ_MIN_DAY 0x08 [0x02 0x02]
CLEAR_MAX_MIN_DAY 0x09
PARAM_CHANGED 0x0a
CLEAR_HISTORY 0x0b
READ_PARAM 0x0c
CMD_RESULT 0xf0
The checksum in each message is simply the lo byte of the sum of the bytes in
each message.
Time Sync (9 bytes)
TIME_SYNC 1
year 1 0x00-0x99 -> 2000 -> 2099
month 1
day 1
hour 1
minute 1
second 1
1/125 second 1 0x00-0x07
checksum 1
Read EEPROM (5 bytes)
READ_EEPROM 1
address 2 lo hi
size 1 1-56
checksum 1
READ_EEPROM 1
size 1 1-56
data x
checksum 1
Write EEPROM (x bytes)
WRITE_EEPROM 1
address 2 lo hi
size 1 1-12
data x
checksum 1
Read Record (2 bytes)
READ_RECORD 1 read the current value
checksum 1
READ_RECORD 1
size 1
data x
checksum 1
Param Changed (4 bytes)
PARAM_CHANGED 1
parameter 2
checksum 1
parameter values:
0x0001 alarm tag or value changed
0x0002 latitude/longitude/timezone changed
0x0004 parameters have changed
0x0008 max/min value has changed
0x0010 history has been emptied
Read Parameter (2 bytes)
READ_PARAM 1
checksum 1
READ_PARAM 1
size 1
data 1
checksum 1
data values:
bit 0: 01: UART 10: ASK 00: FSK
bit 1: 01: UART function 10: ASK function 00: FSK function
bit 2: 1: RCC 0: no RCC
Command Result
CMD_RESULT 1
CMD 1
result 2
checksum 1
return values:
1 RT_SUCCESS
2 RT_INVALID_USER_PASS
3 RT_INVALID_ID
4 RT_INVALID_CRC
5 RT_BUSY
6 RT_TOO_SIZE
7 RT_ERROR
8 RT_UNKNOWN_CMD
9 RT_INVALID_PARAM
"""
import logging
import time
import usb
import weewx.drivers
from weeutil.logger import log_traceback
from weeutil.weeutil import timestamp_to_string
from weewx.wxformulas import calculate_rain
log = logging.getLogger(__name__)
DRIVER_NAME = 'WH23xx'
DRIVER_VERSION = '0.15EZ'
def loader(config_dict, _):
return WH23xxDriver(**config_dict[DRIVER_NAME])
def confeditor_loader():
return WH23xxConfigurationEditor()
def logdbg(msg):
log.debug(msg)
def loginf(msg):
log.info(msg)
def logerr(msg):
log.error(msg)
LUMINOSITY_TO_RADIATION = 0.0079
#' '.join(["%0.2X" % ord(c) for c in buf]))
def _fmt(buf):
if buf:
return "%s (len=%s)" % (' '.join(["%02x" % x for x in buf]), len(buf))
return ''
def _calc_checksum(a):
s = 0
for x in a:
s += x
return s & 0xff
def _get_bit(x, bit):
return 1 if ((x & (1 << bit)) == (1 << bit)) else 0
def _decode_bytes(buf, idx, nbytes, func):
# if all bytes are 0xff, the value is not valid...
for j in range(nbytes):
if buf[idx + j] != 0xff:
break
else:
return None
# ...otherwise, calculate a value from the bytes, MSB first
x = 0
for j in range(nbytes):
x += buf[idx + j] << ((nbytes - j - 1) * 8)
return func(x)
def _signed(x):
v = x & 0xf
if x & 0xf0 == 0xf0:
v *= -1
return v
def _uv_to_uvi(x):
if x < 99:
return 0
elif x < 540:
return 1
elif x < 1000:
return 2
elif x < 1400:
return 3
elif x < 1843:
return 4
elif x < 2292:
return 5
elif x < 2734:
return 6
elif x < 3138:
return 7
elif x < 3648:
return 8
elif x < 4196:
return 9
elif x < 4707:
return 10
elif x < 5209:
return 11
elif x < 5735:
return 12
elif x < 6276:
return 13
elif x < 6778:
return 14
elif x < 20000:
return 15
return 0xff
KNOWN_USB_MESSAGES = [
'No data available', 'No error',
'Nessun dato disponibile', 'Nessun errore',
'Keine Daten verf',
'No hay datos disponibles',
'Pas de donn'
]
# these are the usb 'errors' that should be ignored
def known_usb_err(e):
errmsg = repr(e)
for msg in KNOWN_USB_MESSAGES:
if msg in errmsg:
return True
return False
def get_usb_info():
pyusb_version = '0.4.x'
try:
pyusb_version = usb.__version__
except AttributeError:
pass
return "pyusb_version=%s" % pyusb_version
class WH23xxConfigurationEditor(weewx.drivers.AbstractConfEditor):
@property
def default_stanza(self):
return """
[WH23xx]
# This section is for Fine Offset WH23xx stations
# The model name such as Tycon, or TP2700
model = Tycon TP2700
# The driver to use
driver = user.wh23xx
"""
class WH23xxDriver(weewx.drivers.AbstractDevice):
def __init__(self, **stn_dict):
loginf('init: driver version is %s' % DRIVER_VERSION)
loginf('init: usb info: %s' % get_usb_info())
self._model = stn_dict.get('model', 'Tycon TP2700')
self._poll_interval = int(stn_dict.get('poll_interval', 15))
loginf('init: poll interval is %s seconds' % self._poll_interval)
self.max_tries = int(stn_dict.get('max_tries', 5))
self.retry_wait = int(stn_dict.get('retry_wait', 10))
self._debug_rain = int(stn_dict.get('debug_rain', 0))
self.last_rain = None
self._station = WH23xxStation()
self._station.open()
def closePort(self):
self._station.close()
@property
def hardware_name(self):
return self._model
def genLoopPackets(self):
while True:
raw = self._get_current()
logdbg("genLoopPackets: raw data: %s" % raw)
if raw:
try:
decoded = WH23xxStation.decode_weather_data(raw)
logdbg("genLoopPackets: decoded data: %s" % decoded)
if decoded:
packet = self._data_to_packet(decoded)
logdbg("genLoopPackets: packet: %s" % packet)
yield packet
except IndexError as e:
logerr("genLoopPackets: decode failed: %s (%s)" % (e, _fmt(raw)))
log_traceback(log.debug)
time.sleep(self._poll_interval)
def _get_current(self):
ntries = 0
while ntries < self.max_tries:
ntries += 1
try:
return self._station.get_current()
except usb.USBError as e:
if known_usb_err(e):
logdbg("get_current: %s" % e)
ntries -= 1
else:
logerr("get_current: failed attempt %d of %d: %s" %
(ntries, self.max_tries, e))
except weewx.WeeWxIOError as e:
logerr("get_current: failed attempt %d of %d: %s" %
op
(ntries, self.max_tries, e))
time.sleep(self.retry_wait)
msg = "get_current: read failed: max retries (%d) exceeded" % self.max_tries
logerr(msg)
raise weewx.RetriesExceeded(msg)
def _data_to_packet(self, data):
# convert from the dictionary-of-dictionaries to a simple dictionary
# of observation values.
# FIXME: get measure of connectivity to sensors
# FIXME: get measure of battery life/status
pkt = {'dateTime': int(time.time() + 0.5), 'usUnits': weewx.METRICWX}
pkt['windDir'] = data.get('wind_dir', {}).get('value')
pkt['windSpeed'] = data.get('wind_speed', {}).get('value')
pkt['windGust'] = data.get('gust_speed', {}).get('value')
pkt['inHumidity'] = data.get('in_humidity', {}).get('value')
pkt['outHumidity'] = data.get('out_humidity', {}).get('value')
pkt['inTemp'] = data.get('in_temp', {}).get('value')
pkt['outTemp'] = data.get('out_temp', {}).get('value')
pkt['pressure'] = data.get('abs_baro', {}).get('value')
pkt['luminosity'] = data.get('light', {}).get('value')
pkt['uv_raw'] = data.get('uv', {}).get('value')
pkt['UV'] = data.get('uvi', {}).get('value')
rain_total = data.get('rain_totals', {}).get('value')
# EZ: was calculate_delta in my previous fix, see if this works
# pkt['rain'] = calculate_delta(rain_total, self.last_rain)
pkt['rain'] = calculate_rain(rain_total, self.last_rain)
# EZ: removed rain_rate, see if this works
# pkt['rain_rate'] = data.get('rain_rate', {}).get('value')
if self._debug_rain and self.last_rain != rain_total:
loginf("rain_delta is %s (rain_total=%s, rain_last=%s)" %
(pkt['rain'], rain_total, self.last_rain))
self.last_rain = rain_total
# use luminosity as an approximation for radiation.
# FIXME: this probably should be done by StdWXCalculate
pkt['radiation'] = pkt['luminosity'] * LUMINOSITY_TO_RADIATION if pkt['luminosity'] is not None else None
return pkt
class WH23xxStation(object):
# usb values obtained from 'sudo lsusb -v'
# EZ My USB ids for Renkforce 2300 are
# Device Descriptor:
# idVendor 0x10c4 Cygnal Integrated Products, Inc.
# idProduct 0x8468
# Endpoint Descriptor:
# bEndpointAddress 0x82 EP 2 IN
# wMaxPacketSize 0x0040 1x 64 bytes
# Endpoint Descriptor:
# bEndpointAddress 0x02 EP 2 OUT
# wMaxPacketSize 0x0040 1x 64 bytes
USB_ENDPOINT_IN = 0x82
USB_ENDPOINT_OUT = 0x02
USB_PACKET_SIZE = 0x40 # 64 bytes
# from the vendor documentation
TIME_SYNC = 0x01
READ_EEPROM = 0x02
WRITE_EEPROM = 0x03
READ_RECORD = 0x04
READ_MAX = 0x05
READ_MIN = 0x06
READ_MAX_DAY = 0x07
READ_MIN_DAY = 0x08
CLEAR_MAX_MIN_DAY = 0x09
PARAM_CHANGED = 0x0a
CLEAR_HISTORY = 0x0b
READ_PARAM = 0x0c
CMD_RESULT = 0xf0
PARAM_ITEM_ALARM = 0x0001
PARAM_ITEM_TIMEZONE = 0x0002
PARAM_ITEM_PARAM = 0x0004
PARAM_ITEM_MAX_MIN = 0x0008
PARAM_ITEM_HISTORY = 0x0010
RT_SUCCESS = 0x0000
RT_INVALID_USER_PASS = 0x0001
RT_INVALID_ID = 0x0002
RT_INVALID_CRC = 0x0004
RT_BUSY = 0x0008
RT_TOO_SIZE = 0x0010
RT_ERROR = 0x0020
RT_UNKNOWN_CMD = 0x0040
RT_INVALID_PARAM = 0x0080
INVALID_DATA_8 = 0xff
INVALID_DATA_16 = 0xffff
INVALID_DATA_32 = 0xffffffff
ITEM_INTEMP = 0x01 # C
ITEM_OUTTEMP = 0x02 # C
ITEM_DEWPOINT = 0x03 # C
ITEM_WINDCHILL = 0x04 # C
ITEM_HEATINDEX = 0x05 # C
ITEM_INHUMI = 0x06 # %
ITEM_OUTHUMI = 0x07 # %
ITEM_ABSBARO = 0x08 # mbar
ITEM_RELBARO = 0x09 # mbar
ITEM_WINDDIRECTION = 0x0a # degree
ITEM_WINDSPEED = 0x0b # m/s
ITEM_GUSTSPEED = 0x0c # m/s
ITEM_RAINEVENT = 0x0d # mm
ITEM_RAINRATE = 0x0e # mm/h
ITEM_RAINHOUR = 0x0f # mm
ITEM_RAINDAY = 0x10 # mm
ITEM_RAINWEEK = 0x11 # mm
ITEM_RAINMONTH = 0x12 # mm
ITEM_RAINYEAR = 0x13 # mm
ITEM_RAINTOTALS = 0x14 # mm
ITEM_LIGHT = 0x15 # lux
ITEM_UV = 0x16 # uW/m^2
ITEM_UVI = 0x17 # 0-15 index
ITEM_TIME = 0x40
ITEM_DATE = 0x80
def __init__(self):
# EZ See above Device Descriptor
self.vendor_id = 0x10c4
self.product_id = 0x8468
self.iface = 0
self.timeout = 1000
self.devh = None
def __enter__(self):
self.open()
return self
def __exit__(self, _, value, traceback):
self.close()
def open(self):
dev = self._find_dev(self.vendor_id, self.product_id)
if not dev:
logerr("Cannot find USB device with VendorID=0x%04x ProductID=0x%04x" % (self.vendor_id, self.product_id))
raise weewx.WeeWxIOError('Unable to find station on USB')
self.devh = dev.open()
if not self.devh:
raise weewx.WeeWxIOError('Open USB device failed')
# be sure kernel does not claim the interface on linux systems
try:
self.devh.detachKernelDriver(self.iface)
except (AttributeError, usb.USBError):
pass
# attempt to unwedge the device
self._reset()
# attempt to claim the interface
try:
self.devh.claimInterface(self.iface)
self.devh.setAltInterface(self.iface)
except usb.USBError as e:
logerr("Unable to claim USB interface %s: %s" % (self.iface, e))
self.close()
raise weewx.WeeWxIOError(e)
def close(self):
if self.devh:
try:
self.devh.releaseInterface()
except (ValueError, usb.USBError) as e:
logerr("release interface failed: %s" % e)
self.devh = None
def _reset(self):
# use a usb reset to restore communication with the station.
# specific cases include when you do an interrupt write with bogus
# data. use a reset to bring the station back to responsiveness.
# unfortunately it is not immediate. sometimes it takes one reset.
# sometimes it takes multiple resets.
for x in range(5):
try:
self.devh.reset()
break
except usb.USBError as e:
logdbg("usb reset failed: %s" % e)
time.sleep(2)
@staticmethod
def _find_dev(vendor_id, product_id):
"""Find the vendor and product ID on the USB."""
logdbg("_find_dev: Looking for vendor_id %s and product_id %s..." % (vendor_id, product_id))
for bus in usb.busses():
for dev in bus.devices:
if dev.idVendor == vendor_id and dev.idProduct == product_id:
# EZ: dirname and filename fail on my RPi
#loginf('Found device on USB bus=%s device=%s' % (bus.dirname, dev.filename))
# EZ: So replaced with code that works for me
xdev = usb.core.find(idVendor=dev.idVendor, idProduct=dev.idProduct)
xdev._manufacturer = usb.util.get_string(xdev, xdev.iManufacturer)
xdev._product = usb.util.get_string(xdev, xdev.iProduct)
loginf('Found the device: Manufacturer %s and Product %s' % (xdev._manufacturer, xdev._product))
return dev
return None
def _write(self, label, buf):
logdbg("%s: write: %s" % (label, _fmt(buf)))
cnt = self.devh.interruptWrite(self.USB_ENDPOINT_OUT, buf, self.timeout)
if cnt != len(buf):
raise weewx.WeeWxIOError('%s: bad write length=%s for command %s' %
(label, cnt, _fmt(buf)))
def _time_sync(self, ts):
logdbg("time sync to %s (%s)" % (ts, timestamp_to_string(ts)))
t = time.localtime(ts)
cmd = [WH23xxStation.TIME_SYNC,
t.tm_year - 2000, t.tm_mon, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec, 0]
chksum = _calc_checksum(cmd)
buf = [0x02, 0x09]
buf.extend(cmd)
buf.append(chksum)
self._write("time_sync", buf)
def _read_eeprom(self, addr, size):
# initiate a read by sending the READ_EEPROM command.
addr_lo = addr & 0xff
addr_hi = (addr / 256) & 0xff
cmd = [WH23xxStation.READ_EEPROM, addr_lo, addr_hi, size]
chksum = _calc_checksum(cmd)
buf = [0x02, 0x05]
buf.extend(cmd)
buf.append(chksum)
self._write("read_eeprom", buf)
# now do the actual read.
buf = self.devh.interruptRead(
self.USB_ENDPOINT_IN,
self.USB_PACKET_SIZE,
self.timeout)
if not buf:
raise weewx.WeeWxIOError('read_eeprom failed: empty read')
logdbg("read_eeprom: buf: %s" % _fmt(buf))
if buf[0] != 0x01 or buf[2] != WH23xxStation.READ_EEPROM:
raise weewx.WeeWxIOError('read_eeprom: bad reply: '
'got %02x %02x %02x %02x, '
'exp 01 .. %02x ..' %
(buf[0], buf[1], buf[2], buf[3],
WH23xxStation.READ_EEPROM))
logdbg("read_eeprom: size: %s" % buf[3])
return buf[4:]
def _read_record(self):
# initiate a read by sending the READ_RECORD command.
buf = [0x02, 0x02,
WH23xxStation.READ_RECORD,
WH23xxStation.READ_RECORD]
self._write("read_record", buf)
# now do the actual read. the station should respond with a single
# READ_RECORD response spread over (probably) multiple USB packets.
# each USB packet starts with two bytes, 0x01 followed by the usb
# packet size. we check these, but ignore them. the response
# contains the READ_RECORD reply, the size of the reply data, the
# reply data, and a checksum.
tmp = []
buf = self.devh.interruptRead(
self.USB_ENDPOINT_IN,
self.USB_PACKET_SIZE,
self.timeout)
if not buf:
logdbg("read_record: empty read")
return None
logdbg("read_record: buf: %s" % _fmt(buf))
if buf[0] != 0x01:
raise weewx.WeeWxIOError('read_record: bad first byte: '
'0x%02x != 0x01' % buf[0])
if buf[2] != WH23xxStation.READ_RECORD:
raise weewx.WeeWxIOError('read_record: missing READ_RECORD: '
'0x%02x != 0x%02x' %
(buf[2], WH23xxStation.READ_RECORD))
record_size = buf[3]
logdbg("read_record: record_size: %s" % record_size)
tmp.extend(buf[4:]) # skip 0x01, payload_size, 0x04, record_size
cnt = 0
max_cnt = 20
while len(tmp) < record_size and cnt < max_cnt:
cnt += 1
buf = self.devh.interruptRead(
self.USB_ENDPOINT_IN,
self.USB_PACKET_SIZE,
self.timeout)
logdbg("read_record: buf: %s" % _fmt(buf))
tmp.extend(buf[2:]) # skip 0x01 and payload_size
if cnt >= max_cnt:
raise weewx.WeeWxIOError("read_record: max_cnt reads exceeded")
rbuf = tmp[0:record_size] # prune off any dangling bytes
chksum_pkt = tmp[record_size]
# package up just the bytes we care about
tmp = [WH23xxStation.READ_RECORD, record_size]
tmp.extend(rbuf)
# verify the checksum for the packet
chksum = _calc_checksum(tmp)
logdbg("read_record: rbuf: %s chksum_pkt=%02x chksum=0x%02x" %
(_fmt(rbuf), chksum_pkt, chksum))
if chksum != chksum_pkt:
logerr("read_record: checksum mismatch: 0x%02x != 0x%02x (%s)" %
(chksum_pkt, chksum, _fmt(rbuf)))
raise weewx.WeeWxIOError("read_record: checksum mismatch: "
"%02x != %02x" % (chksum_pkt, chksum))
return rbuf
def _clear_max_min(self):
logdbg("clear max/min")
buf = [0x02, 0x02,
WH23xxStation.CLEAR_MAX_MIN_DAY,
WH23xxStation.CLEAR_MAX_MIN_DAY]
self._write("clear_max_min", buf)
logdbg("max/min cleared")
def _clear_history(self):
logdbg("clear history")
buf = [0x02, 0x02,
WH23xxStation.CLEAR_HISTORY,
WH23xxStation.CLEAR_HISTORY]
self._write("clear_history", buf)
logdbg("history cleared")
def get_current(self):
return self._read_record()
def sync_time(self):
self._time_sync(time.time())
def clear_max_min(self):
self._clear_max_min()
def clear_history(self):
self._clear_history()
def get_station_info(self):
# decode the memory starting at address 0x0, which contains the station
# status and configuration info. return the data as a dictionary.
buf = self._read_eeprom(0x0000, 56)
return self.decode_station_info(buf)
# this map associates the item identifier with [label, num_bytes, function]
# required for decoding weather data from raw bytes.
ITEM_MAPPING = {
ITEM_INTEMP: ['in_temp', 2, lambda x : x / 10.0 - 40.0],
ITEM_OUTTEMP: ['out_temp', 2, lambda x : x / 10.0 - 40.0],
ITEM_DEWPOINT: ['dewpoint', 2, lambda x : x / 10.0 - 40.0],
ITEM_WINDCHILL: ['windchill', 2, lambda x : x / 10.0 - 40.0],
ITEM_HEATINDEX: ['heatindex', 2, lambda x : x / 10.0 - 40.0],
ITEM_INHUMI: ['in_humidity', 1, lambda x : x],
ITEM_OUTHUMI: ['out_humidity', 1, lambda x : x],
ITEM_ABSBARO: ['abs_baro', 2, lambda x : x / 10.0],
ITEM_RELBARO: ['rel_baro', 2, lambda x : x / 10.0],
ITEM_WINDDIRECTION: ['wind_dir', 2, lambda x : x],
ITEM_WINDSPEED: ['wind_speed', 2, lambda x : x / 10.0],
ITEM_GUSTSPEED: ['gust_speed', 2, lambda x : x / 10.0],
ITEM_RAINEVENT: ['rain_event', 4, lambda x : x / 10.0],
ITEM_RAINRATE: ['rain_rate', 4, lambda x : x / 10.0],
ITEM_RAINHOUR: ['rain_hour', 4, lambda x : x / 10.0],
ITEM_RAINDAY: ['rain_day', 4, lambda x : x / 10.0],
ITEM_RAINWEEK: ['rain_week', 4, lambda x : x / 10.0],
ITEM_RAINMONTH: ['rain_month', 4, lambda x : x / 10.0],
ITEM_RAINYEAR: ['rain_year', 4, lambda x : x / 10.0],
ITEM_RAINTOTALS: ['rain_totals', 4, lambda x : x / 10.0],
ITEM_LIGHT: ['light', 4, lambda x : x / 10.0],
ITEM_UV: ['uv', 2, lambda x : x ],
ITEM_UVI: ['uvi', 1, lambda x : x],
}
@staticmethod
def decode_weather_data(raw):
# decode a sequence of bytes into current weather data. the sequence
# can be variable length. an identifier byte is followed by one to
# four data bytes. identifier bytes have a value of ITEM_* bitwise
# or with date and/or time if there is an associated time.
#
# so we simply walk the array, decoding as we go. put the result into
# a dictionary that contains a dictionary for each observation.
#
# if there is a failure, log it and bail out.
data = dict()
i = 0
while i < len(raw):
item = item_raw = raw[i]
i += 1
has_date = (item & WH23xxStation.ITEM_DATE) != 0
has_time = (item & WH23xxStation.ITEM_TIME) != 0
if has_date:
item = item & ~WH23xxStation.ITEM_DATE
if has_time:
item = item & ~WH23xxStation.ITEM_TIME
label = None
obs = dict()
mapping = WH23xxStation.ITEM_MAPPING.get(item)
if mapping:
if i + mapping[1] - 1 >= len(raw):
logerr("decode_weather_data: not enough bytes for %s: idx=%s nbytes=%s bytes=%s"
% (mapping[0], i, mapping[1], raw))
return dict()
# bytes are decoded MSB first, then function is applied
label = mapping[0]
obs['value'] = _decode_bytes(raw, i, mapping[1], mapping[2])
i += mapping[1]
else:
logerr("decode_weather_data: no mapping for item id 0x%02x (0x%02x)"
" at index %s of %s" % (item, item_raw, i-1, _fmt(raw)))
return dict()
if has_date:
# year.month.day
obs['date'] = "%04d.%02d.%02d" % (
2000 + raw[i], raw[i+1], raw[i+2])
i += 3
if has_time:
# hour:minute
obs['time'] = "%02d:%02d" % (raw[i], raw[i+1])
i += 2
# workaround firmware bug for invalid light value
if (item == WH23xxStation.ITEM_LIGHT and
obs['value'] == 0xffffff / 10.0):
obs['value'] = None
logdbg("decode_weather_data: %s: %s (0x%02x 0x%02x)" % (label, obs, item, item_raw))
data[label] = obs
return data
@staticmethod
def decode_history_record(raw):
# each record is 18 bytes
#
# NOTE: the docs specify values for invalid that do not make sense:
# light: 0xfff specified, using 0xffffff
# uv: 0xff specified, using 0xffff
# wind_dir: 0x1f specified, using 0x1ff
data = dict()
if not raw:
logdbg("decode_history_record: empty raw data")
return data
if len(raw) != 18:
logdbg("decode_history_record: wrong number of bytes in raw data: %s != 18" % len(raw))
return data
x = ((raw[0] & 0x01) << 8) + raw[1]
data['wind_dir'] = None if x == 0x1ff else x # compass degree
x = (((raw[0] & 0x02) / 0x02) << 8) + raw[2]
data['wind_speed'] = None if x == 0x1ff else x / 10.0 # m/s
x = (((raw[0] & 0x04) / 0x04) << 8) + raw[3]
data['gust_speed'] = None if x == 0x1ff else x / 10.0 # m/s
data['rain_total'] = ((((raw[0] & 0x08) / 0x08) << 16) + (raw[5] << 8) + raw[4]) * 0.1 # 0.0-9999.9 mm
data['rain_overflow'] = (raw[0] & 0x10) / 0x10 # bit 4
data['no_sensors'] = (raw[0] & 0x80) / 0x80 # bit 7
data['humidity_in'] = None if raw[6] == 0xff else raw[6]
data['humidity_out'] = None if raw[7] == 0xff else raw[7]
x = ((raw[9] & 0x0f) << 8) + raw[8]
data['temperature_in'] = None if x == 0xfff else x / 10.0 - 40.0 # C
x = ((raw[9] & 0xf0) << 8) + raw[10]
data['temperature_out'] = None if x == 0xfff else x / 10.0 - 40.0 # C
x = (raw[11] << 8) + raw[12]
data['pressure'] = None if x == 0xffff else x / 10.0 # hpa
x = (raw[15] << 16) + (raw[14] << 8) + raw[13]
data['light'] = None if x == 0xffffff else x / 10.0 # 0.0-300000.0 lux
x = (raw[17] << 8) + raw[16]
data['uv'] = None if x == 0xffff else x # 0-20000 uW/m^2
data['uvi'] = _uv_to_uvi(data['uv'])
return data
@staticmethod
def decode_station_info(raw):
data = dict()
data['eeprom'] = "0x%02x%02x" % (raw[0], raw[1]) # 0x55aa
data['model'] = "0x%02x%02x" % (raw[2], raw[3]) # 0x0023
data['version'] = "0x%02x" % raw[4] # 0x10
data['id'] = "0x%02x%02x%02x%02x" % (raw[5], raw[6], raw[7], raw[8])
for i in range(0, 8):
data['factory_unit_flag_1_bit%s' % i] = _get_bit(raw[0x09], i)
for i in range(0, 8):
data['factory_unit_flag_2_bit%s' % i] = _get_bit(raw[0x0a], i)
for i in range(0, 8):
data['option_1_bit%s' % i] = _get_bit(raw[0x0b], i)
for i in range(0, 8):
data['option_2_bit%s' % i] = _get_bit(raw[0x0c], i)
data['mode'] = 'ASK' if (raw[0x0c] & 0xf0) == 0xf0 else 'UART'
data['lux_to_rad_factor'] = (raw[0x0e] * 256 + raw[0x0d]) / 10.0
for i in range(0, 8):
data['unit_setting_flag_1_bit%s' % i] = _get_bit(raw[0x10], i)
for i in range(0, 8):
data['unit_setting_flag_2_bit%s' % i] = _get_bit(raw[0x11], i)
for i in range(0, 8):
data['display_setting_flag_1_bit%s' % i] = _get_bit(raw[0x12], i)
for i in range(0, 8):
data['display_setting_flag_2_bit%s' % i] = _get_bit(raw[0x13], i)
for i in range(0, 8):
data['display_setting_flag_3_bit%s' % i] = _get_bit(raw[0x14], i)
for i in range(0, 8):
data['alarm_enable_flag_1_bit%s' % i] = _get_bit(raw[0x15], i)
for i in range(0, 8):
data['alarm_enable_flag_2_bit%s' % i] = _get_bit(raw[0x16], i)
for i in range(0, 8):
data['alarm_enable_flag_3_bit%s' % i] = _get_bit(raw[0x17], i)
data['rain_season'] = raw[0x18] # month 1..12
data['interval'] = raw[0x1a] * 256 + raw[0x19] # seconds 8..14400 (240m)
data['lcd_contrast'] = "%s (0x%02x)" % (raw[0x1b]-0x16, raw[0x1b]) # 0x17..0x1f
data['timezone'] = _signed(raw[0x1c]) # -12..12
data['latitude'] = raw[0x1e] * 256 + raw[0x1d]
data['longitude'] = raw[0x20] * 256 + raw[0x1f]
data['weather'] = raw[0x21]
data['storm'] = raw[0x22]
data['offset_temperature_in'] = (raw[0x24] * 256 + raw[0x23]) / 10.0
data['offset_humidity_in'] = raw[0x25]
data['offset_temperature_out'] = (raw[0x27] * 256 + raw[0x26]) / 10.0
data['offset_humidity_out'] = raw[0x28]
data['offset_pressure_abs'] = (raw[0x2a] * 256 + raw[0x29]) / 10.0
data['offset_pressure_rel'] = (raw[0x2c] * 256 + raw[0x2b]) / 10.0
data['offset_wind_dir'] = raw[0x2e] * 256 + raw[0x2d]
data['coefficient_wind'] = raw[0x2f] / 100.0 # 0.1..2.5
data['coefficient_rain'] = raw[0x30] / 100.0 # 0.1..2.5
data['coefficient_light'] = (raw[0x32] * 256 + raw[0x31]) / 100.0 # 0.1..10.0
data['coefficient_uv'] = (raw[0x34] * 256 + raw[0x33]) / 100.0 # 0.1..10.0
return data
# define a main entry point for basic testing of the station. invoke this as
# follows from the weewx root dir:
#
# PYTHONPATH=bin python bin/user/wh23xx.py
if __name__ == '__main__':
INFO_DATA = [
"55 aa 00 23 10 bc 7a 28 28 52 a2 01 02 f3 04 ff 53 a2 01 4a b2 00 00 00 01 2c 01 1b fb 00 00 00 00 03 04 00 00 00 00 00 00 00 00 c3 ff 00 00 64 64 64 00 64 00 ff ff ff 6b",
]
CURRENT_DATA = [
"01 02 8f 02 02 13 03 02 11 04 02 13 05 02 13 06 32 07 63 08 27 f0 09 27 b2 0a 00 5a 0b 00 2b 0c 00 3b 0e 00 00 00 00 10 00 00 00 75 11 00 00 00 a2 12 00 00 00 75 13 00 00 04 c5 14 00 00 04 c5 15 00 ff ff ff 16 ff ff 17 ff",
"01 02 90 02 02 13 03 02 11 04 02 13 05 02 13 06 32 07 63 08 27 f0 09 27 b2 0a 00 5a 0b 00 17 0c 00 21 0e 00 00 00 00 10 00 00 00 75 11 00 00 00 a2 12 00 00 00 75 13 00 00 04 c5 14 00 00 04 c5 15 00 ff ff ff 16 ff ff 17 ff",
]
HISTORY_DATA = [
"",
"",
]
CORE_PARAMETERS = ['eeprom', 'id', 'interval', 'latitude', 'longitude',
'mode', 'model', 'timezone', 'version']
def print_info(x, display_keys=None):
keys = x.keys() if not display_keys else list(set(x.keys()) & set(display_keys))