-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
302 lines (247 loc) · 8.84 KB
/
main.py
File metadata and controls
302 lines (247 loc) · 8.84 KB
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
"""
Raspberry Pi Pico W - Morningstar ProStar to Signal K Bridge
Reads Modbus RTU data from ProStar charge controller via RS-232
and forwards to Signal K server over WiFi.
Hardware:
- Raspberry Pi Pico W
- Waveshare RS-232 interface board
- Morningstar ProStar charge controller
Wiring:
- Pico GP0 (UART0 TX) -> RS-232 board RX
- Pico GP1 (UART0 RX) -> RS-232 board TX
- Pico GND -> RS-232 board GND
- Pico VSYS/3V3 -> RS-232 board VCC
"""
import network
import urequests as requests
import ujson as json
from machine import UART, Pin
import time
import struct
# Configuration
WIFI_SSID = "your_wifi_ssid"
WIFI_PASSWORD = "your_wifi_password"
SIGNALK_HOST = "192.168.1.100" # IP of your Raspberry Pi 4
SIGNALK_PORT = 3000
SIGNALK_PATH = "/signalk/v1/api/vessels/self/electrical/batteries/house"
# Modbus configuration for ProStar
PROSTAR_ADDRESS = 0x01 # Default Modbus address
BAUD_RATE = 9600 # ProStar default baud rate
READ_INTERVAL = 10 # Seconds between reads
# Initialize UART for RS-232 communication
uart = UART(0, baudrate=BAUD_RATE, bits=8, parity=None, stop=1,
tx=Pin(0), rx=Pin(1))
# ProStar Modbus Register Addresses
REGISTERS = {
'battery_voltage': 0x0008, # Battery voltage (V)
'array_voltage': 0x000B, # Array voltage (V)
'load_voltage': 0x000C, # Load voltage (V)
'charge_current': 0x000D, # Charge current (A)
'array_current': 0x000E, # Array current (A)
'load_current': 0x000F, # Load current (A)
'battery_temp': 0x0011, # Battery temperature (C)
'controller_temp': 0x0012, # Controller temperature (C)
'charge_state': 0x001B, # Charge state
'array_power': 0x003A, # Array power (W)
}
def crc16_modbus(data):
"""Calculate Modbus CRC16"""
crc = 0xFFFF
for byte in data:
crc ^= byte
for _ in range(8):
if crc & 0x0001:
crc = (crc >> 1) ^ 0xA001
else:
crc >>= 1
return crc
def build_modbus_request(address, register, count=1):
"""Build Modbus RTU read holding registers request"""
request = bytearray([
address, # Device address
0x03, # Function code: Read Holding Registers
(register >> 8) & 0xFF, # Register address high
register & 0xFF, # Register address low
(count >> 8) & 0xFF, # Number of registers high
count & 0xFF # Number of registers low
])
crc = crc16_modbus(request)
request.append(crc & 0xFF)
request.append((crc >> 8) & 0xFF)
return request
def parse_modbus_response(response):
"""Parse Modbus response and return data bytes"""
if len(response) < 5:
return None
address = response[0]
function = response[1]
byte_count = response[2]
if function & 0x80: # Error response
return None
data = response[3:3+byte_count]
received_crc = response[-2] | (response[-1] << 8)
calculated_crc = crc16_modbus(response[:-2])
if received_crc != calculated_crc:
return None
return data
def read_register(address, register):
"""Read a single register from ProStar"""
request = build_modbus_request(address, register, 1)
# Clear UART buffer
while uart.any():
uart.read()
# Send request
uart.write(request)
# Wait for response (timeout after 1 second)
timeout = time.ticks_ms() + 1000
response = bytearray()
while time.ticks_ms() < timeout:
if uart.any():
response.extend(uart.read())
if len(response) >= 7: # Minimum response length
break
time.sleep_ms(10)
data = parse_modbus_response(response)
if data and len(data) >= 2:
# Convert to signed 16-bit integer
value = struct.unpack('>h', data[0:2])[0]
return value
return None
def read_prostar_data():
"""Read all relevant data from ProStar controller"""
data = {}
# Battery voltage (scaled by 32768/96.667)
raw = read_register(PROSTAR_ADDRESS, REGISTERS['battery_voltage'])
if raw is not None:
data['batteryVoltage'] = raw * 96.667 / 32768.0
# Array voltage
raw = read_register(PROSTAR_ADDRESS, REGISTERS['array_voltage'])
if raw is not None:
data['arrayVoltage'] = raw * 96.667 / 32768.0
# Charge current
raw = read_register(PROSTAR_ADDRESS, REGISTERS['charge_current'])
if raw is not None:
data['chargeCurrent'] = raw * 79.16 / 32768.0
# Array current
raw = read_register(PROSTAR_ADDRESS, REGISTERS['array_current'])
if raw is not None:
data['arrayCurrent'] = raw * 79.16 / 32768.0
# Load current
raw = read_register(PROSTAR_ADDRESS, REGISTERS['load_current'])
if raw is not None:
data['loadCurrent'] = raw * 79.16 / 32768.0
# Battery temperature
raw = read_register(PROSTAR_ADDRESS, REGISTERS['battery_temp'])
if raw is not None:
data['batteryTemperature'] = raw # Already in Celsius
# Charge state
raw = read_register(PROSTAR_ADDRESS, REGISTERS['charge_state'])
if raw is not None:
states = ['Start', 'Night Check', 'Disconnect', 'Night',
'Fault', 'MPPT', 'Absorption', 'Float', 'Equalize', 'Slave']
if 0 <= raw < len(states):
data['chargeState'] = states[raw]
return data
def connect_wifi():
"""Connect to WiFi network"""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to WiFi...')
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
timeout = 20
while not wlan.isconnected() and timeout > 0:
time.sleep(1)
timeout -= 1
print('.', end='')
if wlan.isconnected():
print('\nWiFi connected:', wlan.ifconfig()[0])
return True
else:
print('\nWiFi connection failed')
return False
return True
def send_to_signalk(data):
"""Send data to Signal K server via HTTP PUT"""
if not data:
return False
# Build Signal K delta update
updates = []
if 'batteryVoltage' in data:
updates.append({
'path': 'electrical.batteries.house.voltage',
'value': data['batteryVoltage']
})
if 'chargeCurrent' in data:
updates.append({
'path': 'electrical.batteries.house.current',
'value': data['chargeCurrent']
})
if 'batteryTemperature' in data:
updates.append({
'path': 'electrical.batteries.house.temperature',
'value': data['batteryTemperature'] + 273.15 # Convert to Kelvin
})
if 'chargeState' in data:
updates.append({
'path': 'electrical.batteries.house.meta.chargeState',
'value': data['chargeState']
})
if 'arrayVoltage' in data:
updates.append({
'path': 'electrical.solar.panelVoltage',
'value': data['arrayVoltage']
})
if 'arrayCurrent' in data:
updates.append({
'path': 'electrical.solar.panelCurrent',
'value': data['arrayCurrent']
})
signalk_data = {
'updates': [{
'source': {
'label': 'ProStar',
'type': 'Morningstar ProStar'
},
'timestamp': time.time(),
'values': updates
}]
}
try:
url = f"http://{SIGNALK_HOST}:{SIGNALK_PORT}/signalk/v1/api/vessels/self"
headers = {'Content-Type': 'application/json'}
response = requests.put(url, data=json.dumps(signalk_data), headers=headers)
response.close()
return response.status_code == 200
except Exception as e:
print(f"Error sending to Signal K: {e}")
return False
def main():
"""Main loop"""
print("ProStar to Signal K Bridge Starting...")
# Connect to WiFi
if not connect_wifi():
print("Failed to connect to WiFi. Please check credentials.")
return
print("Starting data collection...")
while True:
try:
# Read data from ProStar
data = read_prostar_data()
if data:
print(f"Read data: {data}")
# Send to Signal K
if send_to_signalk(data):
print("Data sent to Signal K successfully")
else:
print("Failed to send data to Signal K")
else:
print("No data received from ProStar")
# Wait before next read
time.sleep(READ_INTERVAL)
except Exception as e:
print(f"Error in main loop: {e}")
time.sleep(5)
# Run main program
if __name__ == "__main__":
main()