Hi all, I try written a new driver for my Transceiver USB Rfxcom by modifying script found on the Internet.
I have no error message in my log. Here is my driver, the log, weewx.conf, database archive and the terminal. How can I test my database with sensor packet ? -- You received this message because you are subscribed to the Google Groups "weewx-user" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. For more options, visit https://groups.google.com/d/optout.
#!/usr/bin/env python # rfxcom driver for weewx # # Copyright 2016 Matthew Wall, Luc Heijst # # See http://www.gnu.org/licenses/ """rfxcom is a USB device that receives radio transmissions from sensors weather. """ import serial import threading import syslog import time from _struct import unpack import weewx.drivers import weewx.engine DRIVER_NAME = 'rfxcom' DRIVER_VERSION = '0.1' def loader(config_dict, engine): return rfxcomDriver(engine, config_dict) def confeditor_loader(): return rfxcomConfEditor() def configurator_loader(config_dict): return rfxcomConfigurator() def logmsg(level, msg): syslog.syslog(level, 'rfxcom: %s' % msg) def logdbg(msg): logmsg(syslog.LOG_DEBUG, msg) def loginf(msg): logmsg(syslog.LOG_INFO, msg) def logerr(msg): logmsg(syslog.LOG_ERR, msg) class rfxcomDriver(weewx.drivers.AbstractDevice): def __init__(self, engine, config_dict): loginf('driver version is %s' % DRIVER_VERSION) stn_dict = config_dict.get(DRIVER_NAME, {}) self.sensor_map = stn_dict.get('sensor_map', {}) loginf('sensor map is: %s' % self.sensor_map) self.last_rain_count = None self.station = rfxcom(**stn_dict) self.station.open() def startup(self): reading = rfxcom() reading.start() def closePort(self): if self.station is not None: self.station.close() self.station = None @property def hardware_name(self): return 'rfxcom' def genLoopPackets(self): while True: while True: size=self.station.get_readings(1) if len(size) == 1: break size = int(size.encode('hex'), 16) if size == 0: continue readings = self.station.get_readings(size) try: stype = ord(readings[0]) except IndexError: break subtype = ord(readings[1]) data = readings[3:] if stype == 82: result = self.station.processTempHumid(data) elif stype == 85: result = self.station.processRain(data) elif stype == 86: result = self.station.processWind(subtype, data) elif stype == 87: result = self.station.processUV(subtype, data) else: logdbg("Warning: Type %d is unsupported" % stype) if stype == 82 or stype == 85 or stype == 86 or stype == 87: packet = {'dateTime': int(time.time() + 0.5), 'usUnits': weewx.METRICWX} packet.update(result) logdbg("%s" % packet) yield packet class rfxcom(threading.Thread): DEFAULT_PORT = '/dev/ttyUSB0' DEFAULT_BAUDRATE = 38400 DEFAULT_PARITY = serial.PARITY_NONE DEFAULT_STOPBITS = serial.STOPBITS_ONE DEFAULT_BYTESIZE = serial.EIGHTBITS def __init__(self, **cfg): threading.Thread.__init__(self) self.port = cfg.get('port', self.DEFAULT_PORT) loginf('using serial port %s' % self.port) self.baudrate = cfg.get('baudrate', self.DEFAULT_BAUDRATE) loginf('using baudrate %s' % self.baudrate) self.parity = cfg.get('parity', self.DEFAULT_PARITY) loginf('using parity %s' % self.parity) self.stopbits = cfg.get('stopbits', self.DEFAULT_STOPBITS) loginf('using stopbits %s' % self.stopbits) self.bytesize = cfg.get('bytesize', self.DEFAULT_BYTESIZE) loginf('using bytesize %s' % self.bytesize) self.timeout = 1 # seconds self.serial_port = None self.last_rain = None def __enter__(self): self.open() return self def __exit__(self, _, value, traceback): self.close() def open(self): logdbg("open serial port %s" % self.port) self.serial_port = serial.Serial(self.port, self.baudrate, parity=self.parity, stopbits=self.stopbits, bytesize=self.bytesize, timeout=self.timeout) def close(self): if self.serial_port is not None: logdbg("close serial port %s" % self.port) self.serial_port.close() self.serial_port = None def get_readings(self, data): buf = self.serial_port.read(data) return buf def processTempHumid(self, data): # ID_hi, ID_lo, Time, Temperature, Humidity, Flags, Battery & Signal (ID_hi, ID_lo, temp_hi, temp_lo, humidity, sigbat) = unpack(">BBBBBxB", data) packet = dict() name = 'TempHumid' hardware_id = str('%02d' % int((hex(ID_hi))[2:])) + str('%02d' % int((hex(ID_lo))[2:])) temp = ((temp_hi & 0x7F) << 8 | temp_lo) / 10.0 if temp_hi & 0x80: temp = -temp packet['temperature'] = float(temp) packet['humidity'] = int(humidity) packet['signal'] = (sigbat >> 4 & 0x0f) packet['battery'] = (sigbat & 0x0f) return self.add_identifiers(packet, hardware_id, name) def processRain(self, data): # ID_hi, ID_lo, Time, Temperature, Humidity, Flags, Battery & Signal (ID_hi, ID_lo, rate_hi, rate_lo, total_hi, total_mi, total_lo, sigbat) = unpack(">BBBBBBBB", data) packet = dict() packet_type ='Rain' sensor_id = str('%02d' % int((hex(ID_hi))[2:])) + str('%02d' % int((hex(ID_lo))[2:])) packet['rate'] = (rate_hi << 8 | rate_lo) / 100.0 packet['rain_total'] = (total_hi << 16 | total_mi << 8 | total_lo) / 10.0 if self.last_rain is not None: packet['rain'] = packet['rain_total'] - self.last_rain else: packet['rain'] = None self.last_rain = packet['rain_total'] packet['signal'] = (sigbat >> 4 & 0x0f) packet['battery'] =(sigbat & 0x0f) return self.add_identifiers(packet, sensor_id, packet_type) def processUV(self, subtype, data): # ID_hi, ID_lo, Time, UV, Extratemp, Battery & Signal (ID_hi, ID_lo, temp_hi, temp_lo, uv, sigbat) = unpack(">BBBBBB", data) packet = dict() packet_type = "UV" sensor_id = str('%02d' % int((hex(ID_hi))[2:])) + str('%02d' % int((hex(ID_lo))[2:])) temp = ((temp_hi & 0x7F) << 8 | temp_lo) / 10.0 if temp_hi & 0x80: temp = -temp packet['temperature'] = temp packet['uv'] = uv packet['signal'] = (sigbat >> 4 & 0x0f) packet['battery'] =(sigbat & 0x0f) if subtype == 3: packet['Extratemp'] = ", %.1fC" % temp else: packet['Extratemp'] = "" return self.add_identifiers(packet, sensor_id, packet_type) def processWind(self, subtype, data): # ID_hi, ID_lo, Time, Direction, Average Speed, Speed, Battery & Signal (ID_hi, ID_lo, wind_hi, wind_lo, avg_hi, avg_lo, speed_hi, speed_lo, temp_hi, temp_lo, chill_hi, chill_lo, sigbat) = unpack(">BBBBBBBBBBBBB", data) packet = dict() packet_type = 'Wind' sensor_id = str('%02d' % int((hex(ID_hi))[2:])) + str('%02d' % int((hex(ID_lo))[2:])) packet['wind'] = wind_hi << 8 | wind_lo packet['average'] = (avg_hi << 8 | avg_lo) / 10 packet['speed'] = (speed_hi << 8 | speed_lo) / 10 temp = ((temp_hi & 0x7F) << 8 | temp_lo) / 10.0 if temp_hi & 0x80: temp = -temp packet['temperature'] = temp chill = ((chill_hi & 0x7F) << 8 | chill_lo) / 10.0 if chill_hi & 0x80: chill = -chill packet['chill'] = chill packet['signal'] = (sigbat >> 4 & 0x0f) packet['battery'] =(sigbat & 0x0f) if subtype == 4: packet['Extratemp'] = " %.1fC" % temp packet['Extrachill'] = " %.1fCF" % chill else: packet['Extratemp'] = "" packet['Extrachill'] = "" return self.add_identifiers(packet, sensor_id, packet_type) @staticmethod def add_identifiers(pkt, sensor_id='', packet_type=''): # qualify each field name with details about the sensor. not every # sensor has all three fields. # observation.<sensor_id>.<packet_type> packet = dict() if 'dateTime' in pkt: packet['dateTime'] = pkt.pop('dateTime', 0) if 'usUnits' in pkt: packet['usUnits'] = pkt.pop('usUnits', 0) for n in pkt: packet["%s.%s.%s" % (n, sensor_id, packet_type)] = pkt[n] return packet class rfxcomConfEditor(weewx.drivers.AbstractConfEditor): @property def default_stanza(self): return """ [rfxcom] # This section is for the rfxcom USB receiver. # The serial port to which the rfxcom transceiver is attached, e.g., /dev/ttyS0 port = /dev/ttyUSB0 # The driver to use driver = user.rfxcom [[sensor_map]] outTemp = temperature.5501.TempHumid outHumidity = humidity.5501.TempHumid rain_total = rain_total.1500.Rain """ def prompt_for_settings(self): settings = dict() print "Specify the serial port on which the rfxcom is connected," print "for example /dev/ttyUSB0 or /dev/ttyS0" settings['port'] = self._prompt('port', rfxcom.DEFAULT_PORT) return settings class rfxcomConfigurator(weewx.drivers.AbstractConfigurator): def add_options(self, parser): super(rfxcomConfigurator, self).add_options(parser) parser.add_option( "--info", dest="info", action="store_true", help="display rfxcom configuration") parser.add_option( "--show-options", dest="opts", action="store_true", help="display rfxcom command options") parser.add_option( "--set-verbose", dest="verbose", metavar="X", type=int, help="set verbose: 0=off, 1=on; default off") parser.add_option( "--set-debug", dest="debug", metavar="X", type=int, help="set debug: 0=off, 1=on; default off") # bug in meteostick: according to docs, 0=high, 1=low def do_options(self, options, parser, config_dict, prompt): driver = rfxcomDriver(None, config_dict) info = driver.station.reset() if options.info: print info cfg = { 'd': options.debug, 'v': options.verbose} for opt in cfg: if cfg[opt]: cmd = opt + cfg[opt] print "set station parameter %s" % cmd driver.station.send_command(cmd) if options.opts: driver.station.send_command('?') print driver.station.get() driver.closePort() # define a main entry point for basic testing of the station without weewx # engine and service overhead. invoke this as follows from the weewx root dir: # # PYTHONPATH=bin python bin/user/rfxcom.py if __name__ == '__main__': import optparse usage = """%prog [options] [--help]""" syslog.openlog('rfxcom', syslog.LOG_PID | syslog.LOG_CONS) syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display driver version') parser.add_option('--port', dest='port', metavar='PORT', help='serial port to which the station is connected', default=rfxcom.DEFAULT_PORT) parser.add_option('--baudrate', dest='baudrate', metavar='BAUDRATE', help='serial port baudrate', default=rfxcom.DEFAULT_BAUDRATE) parser.add_option('--parity', dest='parity', metavar='PARITY', help='serial port parity', default=rfxcom.DEFAULT_PARITY) parser.add_option('--stopbits', dest='stopbits', metavar='STOPBITS', help='serial port stopbits', default=rfxcom.DEFAULT_STOPBITS) parser.add_option('--bytesize', dest='bytesize', metavar='BYTESIZE', help='serial port bytesize', default=rfxcom.DEFAULT_BYTESIZE) (opts, args) = parser.parse_args() if opts.version: print "rfxcom driver version %s" % DRIVER_VERSION exit(0) with rfxcom(port = opts.port, baudrate = opts.baudrate, parity = opts.parity, stopbits = opts.stopbits, bytesize = opts.bytesize) as s: while True: print time.time(), s.get_readings()
# WEEWX CONFIGURATION FILE # # Copyright (c) 2009-2015 Tom Keffer <[email protected]> # See the file LICENSE.txt for your rights. ############################################################################## # This section is for general configuration information. # Set to 1 for extra debug info, otherwise comment it out or set to zero debug = 1 # Root directory of the weewx data file hierarchy for this station WEEWX_ROOT = /home/weewx # How long to wait before timing out a socket (FTP, HTTP) connection socket_timeout = 20 # Do not modify this. It is used when installing and updating weewx. version = 3.7.1 ############################################################################## # This section is for information about the station. [Station] # Description of the station location location = test # Latitude and longitude in decimal degrees latitude = 90.000 longitude = 0.000 # Altitude of the station, with unit it is in. This is downloaded from # from the station if the hardware supports it. altitude = 0, meter # Choose 'foot' or 'meter' for unit # Set to type of station hardware. There must be a corresponding stanza # in this file with a 'driver' parameter indicating the driver to be used. station_type = rfxcom # If you have a website, you may specify an URL #station_url = http://www.example.com # The start of the rain year (1=January; 10=October, etc.). This is # downloaded from the station if the hardware supports it. rain_year_start = 1 # Start of week (0=Monday, 6=Sunday) week_start = 6 [rfxcom] driver = user.rfxcom [[sensor_map]] outTemp = temperature.5501.TempHumid outHumidity = humidity.5501.TempHumid rain_total = rain_total.1500.Rain ############################################################################## # This section is for uploading data to Internet sites [StdRESTful] [[StationRegistry]] # To register this weather station with weewx, set this to true register_this_station = false [[AWEKAS]] # This section is for configuring posts to AWEKAS. # If you wish to do this, set the option 'enable' to true, # and specify a username and password. enable = false username = replace_me # To guard against parsing errors, put your password in quotes: password = replace_me [[CWOP]] # This section is for configuring posts to CWOP. # If you wish to do this, set the option 'enable' to true, # and specify the station ID (e.g., CW1234). enable = false station = replace_me # If this is an APRS (radio amateur) station, uncomment # the following and replace with a passcode (e.g., 12345). #passcode = replace_me (APRS stations only) [[PWSweather]] # This section is for configuring posts to PWSweather.com. # If you wish to do this, set the option 'enable' to true, # and specify a station and password. enable = false station = replace_me # To guard against parsing errors, put your password in quotes: password = replace_me [[WOW]] # This section is for configuring posts to WOW. # If you wish to do this, set the option 'enable' to true, # and specify a station and password. enable = false station = replace_me # To guard against parsing errors, put your password in quotes: password = replace_me [[Wunderground]] # This section is for configuring posts to the Weather Underground. # If you wish to do this, set the option 'enable' to true, # and specify a station (e.g., 'KORHOODR3') and password. enable = false station = replace_me # To guard against parsing errors, put your password in quotes: password = replace_me # Set the following to True to have weewx use the WU "Rapidfire" # protocol. Not all hardware can support it. See the User's Guide. rapidfire = False ############################################################################## # This section specifies what reports, using which skins, to generate. [StdReport] # Where the skins reside, relative to WEEWX_ROOT SKIN_ROOT = skins # Where the generated reports should go, relative to WEEWX_ROOT HTML_ROOT = public_html # The database binding indicates which data should be used in reports. data_binding = wx_binding # Each of the following subsections defines a report that will be run. [[StandardReport]] # See the customizing guide to change the units, plot types and line # colors, modify the fonts, display additional sensor data, and other # customizations. Many of those changes can be made here by overriding # parameters, or by modifying templates within the skin itself. # The StandardReport uses the 'Standard' skin, which contains the # images, templates and plots for the report. skin = Standard [[[Units]]] [[[[Groups]]]] group_altitude = meter group_speed2 = meter_per_second2 group_pressure = mbar group_rain = mm group_rainrate = mm_per_hour group_temperature = degree_C group_degree_day = degree_C_day group_speed = meter_per_second [[FTP]] # FTP'ing the results to a webserver is treated as just another report, # albeit one with an unusual report generator! skin = Ftp # If you wish to use FTP, uncomment and fill out the next four lines. #user = replace with the ftp username #password = replace with the ftp password; put in quotes to guard against parsing errors. #server = replace with the ftp server name, e.g, www.threefools.org #path = replace with the ftp destination directory (e.g., /weather) # Set to True for an FTP over TLS (FTPS) connection. Not all servers # support this. secure_ftp = False # To upload files from something other than what HTML_ROOT is set # to above, specify a different HTML_ROOT here. #HTML_ROOT = public_html # Most FTP servers use port 21 port = 21 # Set to 1 to use passive mode, zero for active mode passive = 1 [[RSYNC]] # rsync'ing to a webserver is treated as just another report skin = Rsync # If you wish to use rsync, you must configure passwordless ssh using # public/private key authentication from the user account that weewx # runs as to the user account on the remote machine where the files # will be copied. # # The following three lines determine where files will be sent. #server = replace with the rsync server name, e.g, www.threefools.org #path = replace with the rsync destination directory (e.g., /weather) #user = replace with the rsync username # Rsync can be configured to remove files from the remote server if # they don't exist under HTML_ROOT locally. USE WITH CAUTION: if you # make a mistake in the remote path, you could could unintentionally # cause unrelated files to be deleted. Set to 1 to enable remote file # deletion, zero to allow files to accumulate remotely. delete = 0 ############################################################################## # This service acts as a filter, converting the unit system coming from # the hardware to a unit system in the database. [StdConvert] # The target_unit affects only the unit system in the database. Once # chosen it cannot be changed without converting the entire database. # Modification of target_unit after starting weewx will result in # corrupt data - the database will contain a mix of US and METRIC data. # # The value of target_unit does not affect the unit system for # reporting - reports can display US, Metric, or any combination of units. # # In most cases, target_unit should be left as the default: US # # In particular, those migrating from a standard wview installation # should use US since that is what the wview database contains. # DO NOT MODIFY THIS VALUE UNLESS YOU KNOW WHAT YOU ARE DOING! target_unit = METRICWX # Options are 'US', 'METRICWX', or 'METRIC' ############################################################################## # This section can adjust data using calibration expressions. [StdCalibrate] [[Corrections]] # For each type, an arbitrary calibration expression can be given. # It should be in the units defined in the StdConvert section. # Example: foo = foo + 0.2 ############################################################################## # This section is for quality control checks. If units are not specified, # values must be in the units defined in the StdConvert section. [StdQC] [[MinMax]] barometer = 26, 32.5, inHg outTemp = -40, 120, degree_F inTemp = 10, 120, degree_F outHumidity = 0, 100 inHumidity = 0, 100 windSpeed = 0, 120, mile_per_hour pressure = 24, 34.5, inHg ############################################################################## # This section controls the origin of derived values. [StdWXCalculate] [[Calculations]] # Derived quantities are calculated by this service. Possible values are: # hardware - use the value provided by hardware # software - use the value calculated by weewx # prefer_hardware - use value provide by hardware if available, # otherwise use value calculated by weewx pressure = prefer_hardware barometer = prefer_hardware altimeter = prefer_hardware windchill = prefer_hardware heatindex = prefer_hardware dewpoint = prefer_hardware inDewpoint = prefer_hardware rainRate = prefer_hardware ############################################################################## # For hardware that supports it, this section controls how often the # onboard clock gets updated. [StdTimeSynch] # How often to check the weather station clock for drift (in seconds) clock_check = 14400 # How much it can drift before we will correct it (in seconds) max_drift = 5 ############################################################################## # This section is for configuring the archive service. [StdArchive] # If the station hardware supports data logging then the archive interval # will be downloaded from the station. Otherwise, specify it (in seconds). archive_interval = 300 # If possible, new archive records are downloaded from the station # hardware. If the hardware does not support this, then new archive # records will be generated in software. # Set the following to "software" to force software record generation. record_generation = software # Whether to include LOOP data in hi/low statistics loop_hilo = True # The data binding used to save archive records data_binding = wx_binding ############################################################################## # This section binds a data store to a database. [DataBindings] [[wx_binding]] # The database must match one of the sections in [Databases]. # This is likely to be the only option you would want to change. database = archive_mysql # The name of the table within the database table_name = archive # The manager handles aggregation of data for historical summaries manager = weewx.wxmanager.WXDaySummaryManager # The schema defines the structure of the database. # It is *only* used when the database is created. schema = schemas.wview.schema ############################################################################## # This section defines various databases. [Databases] # A SQLite database is simply a single file [[archive_sqlite]] database_type = SQLite database_name = weewx.sdb # MySQL [[archive_mysql]] database_type = MySQL database_name = weewx ############################################################################## # This section defines defaults for the different types of databases. [DatabaseTypes] # Defaults for SQLite databases [[SQLite]] driver = weedb.sqlite # Directory in which the database files are located SQLITE_ROOT = %(WEEWX_ROOT)s/archive # Defaults for MySQL databases [[MySQL]] driver = weedb.mysql # The host where the database is located host = localhost # The user name for logging in to the host user = weewx # The password for the user name. Put in quotes to guard against parsing errors. password = weewx ############################################################################## # This section configures the internal weewx engine. [Engine] [[Services]] # This section specifies the services that should be run. They are # grouped by type, and the order of services within each group # determines the order in which the services will be run. prep_services = weewx.engine.StdTimeSynch data_services = , process_services = weewx.engine.StdConvert, weewx.engine.StdCalibrate, weewx.engine.StdQC, weewx.wxservices.StdWXCalculate archive_services = weewx.engine.StdArchive restful_services = weewx.restx.StdStationRegistry, weewx.restx.StdWunderground, weewx.restx.StdPWSweather, weewx.restx.StdCWOP, weewx.restx.StdWOW, weewx.restx.StdAWEKAS report_services = weewx.engine.StdPrint, weewx.engine.StdReport ##############################################################################
syslog
Description: Binary data
terminal
Description: Binary data
"dateTime","usUnits","interval","barometer","pressure","altimeter","inTemp","outTemp","inHumidity","outHumidity","windSpeed","windDir","windGust","windGustDir","rainRate","rain","dewpoint","windchill","heatindex","ET","radiation","UV","extraTemp1","extraTemp2","extraTemp3","soilTemp1","soilTemp2","soilTemp3","soilTemp4","leafTemp1","leafTemp2","extraHumid1","extraHumid2","soilMoist1","soilMoist2","soilMoist3","soilMoist4","leafWet1","leafWet2","rxCheckPercent","txBatteryStatus","consBatteryVoltage","hail","hailRate","heatingTemp","heatingVoltage","supplyVoltage","referenceVoltage","windBatteryStatus","rainBatteryStatus","outTempBatteryStatus","inTempBatteryStatus" "1496183700","17","5",NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
