29 Commits

Author SHA1 Message Date
c94f5bdb45 get log to work, make time accessible 2025-09-20 11:31:51 +02:00
584d6df2d0 file up & download and delete 2025-09-18 01:39:32 +02:00
cd63e76469 set read config initial somewhat ready 2025-09-17 03:50:21 +02:00
4c54edbcea littlefs2 impl stuff 2025-09-17 01:36:53 +02:00
8b938e7687 small adjustments 2025-09-16 22:41:45 +02:00
1c84cd00da rework wifi controller share 2025-09-16 02:24:03 +02:00
1397f5d775 keep ota around for alter queries to it 2025-09-16 01:41:38 +02:00
65f6670ca4 adda lot of basic webserver back 2025-09-15 01:21:50 +02:00
049a9d027c use ssid 2025-09-14 13:50:46 +02:00
4aa25c687b minimal startup running 2025-09-14 13:19:30 +02:00
b3cc313139 initial webserver stub running 2025-09-14 05:29:23 +02:00
be3c4a5095 startup and ota state detection working, now wifi_ap next 2025-09-13 20:56:11 +02:00
4160202cdc more changes and linking 2025-09-13 02:47:53 +02:00
9de85b6e37 it's alive 2025-09-13 01:39:47 +02:00
79087c9353 more async migration 2025-09-12 16:30:35 +02:00
0d495d0f56 probalby found most of the import related stuff, now the real refactor begins 2025-09-12 00:05:52 +02:00
242e748ca0 started cleanup and moving from std to no_std 2025-09-11 22:47:11 +02:00
f853b6f2b2 removed all std dependencies … WIP move to embassy pure rust code 2025-09-11 21:42:17 +02:00
5bc20d312a Merge branch 'feature/enable-mqtt-login' into develop 2025-09-11 20:21:34 +02:00
4faae86a6b reduce amount of warnings 2025-09-11 20:17:18 +02:00
4fa1a05fc3 remove duplicate import 2025-09-11 20:04:27 +02:00
3a24dcec53 add release profile 2025-09-11 19:56:53 +02:00
e7895577ca update frontent to include inputs for mqtt auth 2025-09-11 19:56:50 +02:00
be9a076b33 add configuration options to enable mqtt user login 2025-09-11 19:56:48 +02:00
47ad4c70de Merge branch 'can' into develop 2025-09-03 19:08:55 +02:00
c4aa3a1450 1.3 baseplane 2025-08-29 21:11:04 +02:00
f0d89417b6 Merge branch 'premerge' into develop 2025-08-29 21:09:20 +02:00
a8e17cda3b wip min 2025-08-29 17:14:15 +02:00
a38d704498 new case and can sensor board 2025-08-25 10:15:36 +02:00
60 changed files with 51267 additions and 4886 deletions

BIN
board/Body1.3mf Normal file

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"board": {
"active_layer": 4,
"active_layer": 0,
"active_layer_preset": "All Layers",
"auto_track_width": false,
"hidden_netclasses": [],

View File

@@ -472,6 +472,7 @@
"single_global_label": "ignore",
"unannotated": "error",
"unconnected_wire_endpoint": "warning",
"undefined_netclass": "error",
"unit_value_mismatch": "error",
"unresolved_variable": "error",
"wire_dangling": "error"

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-battery-charging" viewBox="0 0 16 16">
<path d="M9.585 2.568a.5.5 0 0 1 .226.58L8.677 6.832h1.99a.5.5 0 0 1 .364.843l-5.334 5.667a.5.5 0 0 1-.842-.49L5.99 9.167H4a.5.5 0 0 1-.364-.843l5.333-5.667a.5.5 0 0 1 .616-.09z"/>
<path d="M2 4h4.332l-.94 1H2a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h2.38l-.308 1H2a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2"/>
<path d="M2 6h2.45L2.908 7.639A1.5 1.5 0 0 0 3.313 10H2zm8.595-2-.308 1H12a1 1 0 0 1 1 1v4a1 1 0 0 1-1 1H9.276l-.942 1H12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2z"/>
<path d="M12 10h-1.783l1.542-1.639q.146-.156.241-.34zm0-3.354V6h-.646a1.5 1.5 0 0 1 .646.646M16 8a1.5 1.5 0 0 1-1.5 1.5v-3A1.5 1.5 0 0 1 16 8"/>
</svg>

After

Width:  |  Height:  |  Size: 738 B

View File

@@ -182,40 +182,40 @@
)
(pad "9" thru_hole rect
(at 39.5 22.5)
(size 0.85 0.85)
(drill 0.5)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "f01565c2-eadd-4451-9dea-2ebe28d872f0")
)
(pad "10" thru_hole rect
(at -0.5 15)
(size 0.85 0.85)
(drill 0.5)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "56ec7c50-069f-4f46-9b83-ac18e4928930")
)
(pad "11" thru_hole rect
(at -43 22.5)
(size 0.85 0.85)
(drill 0.5)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "f423be21-13b8-46de-8e19-e48325411a29")
)
(pad "12" thru_hole rect
(at -0.5 -12)
(size 0.85 0.85)
(drill 0.5)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "536f0038-06c5-45e5-b1c8-898a364f6ec4")
)
(pad "13" thru_hole rect
(at 39.5 -16)
(size 0.85 0.85)
(drill 0.5)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "3e0cdbaa-8219-48c4-bb0a-fd4f0e78a390")

View File

@@ -0,0 +1,208 @@
(footprint "Sensor"
(version 20241229)
(generator "pcbnew")
(generator_version "9.0")
(layer "F.Cu")
(property "Reference" "REF**"
(at 0 -0.5 0)
(unlocked yes)
(layer "F.SilkS")
(uuid "f71e9c26-7923-4e5c-828e-153927862740")
(effects
(font
(size 1 1)
(thickness 0.1)
)
)
)
(property "Value" "Sensor"
(at 0 1 0)
(unlocked yes)
(layer "F.Fab")
(uuid "d40c7203-0c06-49e1-8672-dbd216694fc8")
(effects
(font
(size 1 1)
(thickness 0.15)
)
)
)
(property "Datasheet" ""
(at 0 0 0)
(unlocked yes)
(layer "F.Fab")
(hide yes)
(uuid "6720cb18-0687-4d55-a6ad-3ccf0819eac2")
(effects
(font
(size 1 1)
(thickness 0.15)
)
)
)
(property "Description" ""
(at 0 0 0)
(unlocked yes)
(layer "F.Fab")
(hide yes)
(uuid "43905e6e-773d-4d5e-8d72-57c092c3495a")
(effects
(font
(size 1 1)
(thickness 0.15)
)
)
)
(attr smd)
(fp_line
(start -45 -18)
(end 41 -18)
(stroke
(width 0.1)
(type default)
)
(layer "F.SilkS")
(uuid "e63ec799-95c4-407e-acc9-9c7e6d3e330c")
)
(fp_line
(start -45 24)
(end -45 -18)
(stroke
(width 0.1)
(type default)
)
(layer "F.SilkS")
(uuid "a66c286b-432b-493d-9619-2dd4fbfdb21c")
)
(fp_line
(start -44 24)
(end -45 24)
(stroke
(width 0.1)
(type default)
)
(layer "F.SilkS")
(uuid "71526e68-71d4-4b13-ab74-482657a06849")
)
(fp_line
(start 41 -18)
(end 41 24)
(stroke
(width 0.1)
(type default)
)
(layer "F.SilkS")
(uuid "55554342-bbff-4d1b-b931-67fb7eaa5895")
)
(fp_line
(start 41 24)
(end -44 24)
(stroke
(width 0.1)
(type default)
)
(layer "F.SilkS")
(uuid "2dc0ee59-36f6-407e-821a-c6acfe3ea887")
)
(fp_text user "${REFERENCE}"
(at 0 2.5 0)
(unlocked yes)
(layer "F.Fab")
(uuid "befc0725-b201-4f81-b0dc-b327becad9ba")
(effects
(font
(size 1 1)
(thickness 0.15)
)
)
)
(pad "1" thru_hole rect
(at -42.4 -15.3)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "5538ac99-6e48-4111-a3df-8ff33be72ff3")
)
(pad "2" thru_hole circle
(at -42.4 -12.76)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "0c1d4a6c-7871-46ae-a262-a8223571975e")
)
(pad "3" thru_hole circle
(at -42.4 -10.22)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "70df4148-0415-45a2-8365-0977fcda45a1")
)
(pad "4" thru_hole circle
(at -42.4 -7.68)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "179dd332-2ab2-4917-91ec-35f232b45ce3")
)
(pad "5" thru_hole circle
(at -42.4 -5.14)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "17bc8f3a-4727-4e31-90f4-8252dff5ad1c")
)
(pad "6" thru_hole circle
(at -42.4 -2.6)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "eee06414-e977-45a8-a5e0-618644284d45")
)
(pad "7" thru_hole rect
(at -0.5 -12)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "536f0038-06c5-45e5-b1c8-898a364f6ec4")
)
(pad "8" thru_hole rect
(at 39.5 -16)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "3e0cdbaa-8219-48c4-bb0a-fd4f0e78a390")
)
(pad "9" thru_hole rect
(at 39.5 22.5)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "f01565c2-eadd-4451-9dea-2ebe28d872f0")
)
(pad "10" thru_hole rect
(at -0.5 15)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "56ec7c50-069f-4f46-9b83-ac18e4928930")
)
(pad "11" thru_hole rect
(at -43 22.5)
(size 1.7 1.7)
(drill 1)
(layers "*.Cu" "*.Mask")
(remove_unused_layers no)
(uuid "f423be21-13b8-46de-8e19-e48325411a29")
)
(embedded_fonts no)
)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,136 @@
{
"board": {
"active_layer": 6,
"active_layer_preset": "All Layers",
"auto_track_width": false,
"hidden_netclasses": [],
"hidden_nets": [],
"high_contrast_mode": 0,
"net_color_mode": 1,
"opacity": {
"images": 0.6,
"pads": 1.0,
"shapes": 1.0,
"tracks": 1.0,
"vias": 1.0,
"zones": 0.6
},
"selection_filter": {
"dimensions": true,
"footprints": true,
"graphics": true,
"keepouts": true,
"lockedItems": false,
"otherItems": true,
"pads": true,
"text": true,
"tracks": true,
"vias": true,
"zones": true
},
"visible_items": [
"vias",
"footprint_text",
"footprint_anchors",
"ratsnest",
"grid",
"footprints_front",
"footprints_back",
"footprint_values",
"footprint_references",
"tracks",
"drc_errors",
"drawing_sheet",
"bitmaps",
"pads",
"zones",
"drc_warnings",
"locked_item_shadows",
"conflict_shadows",
"shapes"
],
"visible_layers": "ffffffff_ffffffff_ffffffff_ffffffff",
"zone_display_mode": 1
},
"git": {
"repo_type": "",
"repo_username": "",
"ssh_key": ""
},
"meta": {
"filename": "Sensors.kicad_prl",
"version": 5
},
"net_inspector_panel": {
"col_hidden": [
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false
],
"col_order": [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
],
"col_widths": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
"custom_group_rules": [],
"expanded_rows": [],
"filter_by_net_name": true,
"filter_by_netclass": true,
"filter_text": "",
"group_by_constraint": false,
"group_by_netclass": false,
"show_unconnected_nets": false,
"show_zero_pad_nets": false,
"sort_ascending": true,
"sorting_column": 0
},
"open_jobsets": [],
"project": {
"files": []
},
"schematic": {
"selection_filter": {
"graphics": true,
"images": true,
"labels": true,
"lockedItems": false,
"otherItems": true,
"pins": true,
"symbols": true,
"text": true,
"wires": true
}
}
}

View File

@@ -0,0 +1,674 @@
{
"board": {
"3dviewports": [],
"design_settings": {
"defaults": {
"apply_defaults_to_fp_fields": false,
"apply_defaults_to_fp_shapes": false,
"apply_defaults_to_fp_text": false,
"board_outline_line_width": 0.05,
"copper_line_width": 0.2,
"copper_text_italic": false,
"copper_text_size_h": 1.5,
"copper_text_size_v": 1.5,
"copper_text_thickness": 0.3,
"copper_text_upright": false,
"courtyard_line_width": 0.05,
"dimension_precision": 4,
"dimension_units": 3,
"dimensions": {
"arrow_length": 1270000,
"extension_offset": 500000,
"keep_text_aligned": true,
"suppress_zeroes": true,
"text_position": 0,
"units_format": 0
},
"fab_line_width": 0.1,
"fab_text_italic": false,
"fab_text_size_h": 1.0,
"fab_text_size_v": 1.0,
"fab_text_thickness": 0.15,
"fab_text_upright": false,
"other_line_width": 0.1,
"other_text_italic": false,
"other_text_size_h": 1.0,
"other_text_size_v": 1.0,
"other_text_thickness": 0.15,
"other_text_upright": false,
"pads": {
"drill": 0.8,
"height": 1.27,
"width": 2.54
},
"silk_line_width": 0.1,
"silk_text_italic": false,
"silk_text_size_h": 1.0,
"silk_text_size_v": 1.0,
"silk_text_thickness": 0.1,
"silk_text_upright": false,
"zones": {
"min_clearance": 0.5
}
},
"diff_pair_dimensions": [
{
"gap": 0.0,
"via_gap": 0.0,
"width": 0.0
}
],
"drc_exclusions": [],
"meta": {
"version": 2
},
"rule_severities": {
"annular_width": "error",
"clearance": "error",
"connection_width": "warning",
"copper_edge_clearance": "error",
"copper_sliver": "warning",
"courtyards_overlap": "error",
"creepage": "error",
"diff_pair_gap_out_of_range": "error",
"diff_pair_uncoupled_length_too_long": "error",
"drill_out_of_range": "error",
"duplicate_footprints": "warning",
"extra_footprint": "warning",
"footprint": "error",
"footprint_filters_mismatch": "ignore",
"footprint_symbol_mismatch": "warning",
"footprint_type_mismatch": "ignore",
"hole_clearance": "error",
"hole_to_hole": "warning",
"holes_co_located": "warning",
"invalid_outline": "error",
"isolated_copper": "warning",
"item_on_disabled_layer": "error",
"items_not_allowed": "error",
"length_out_of_range": "error",
"lib_footprint_issues": "warning",
"lib_footprint_mismatch": "warning",
"malformed_courtyard": "ignore",
"microvia_drill_out_of_range": "error",
"mirrored_text_on_front_layer": "warning",
"missing_courtyard": "ignore",
"missing_footprint": "warning",
"net_conflict": "warning",
"nonmirrored_text_on_back_layer": "warning",
"npth_inside_courtyard": "ignore",
"padstack": "warning",
"pth_inside_courtyard": "ignore",
"shorting_items": "error",
"silk_edge_clearance": "ignore",
"silk_over_copper": "warning",
"silk_overlap": "warning",
"skew_out_of_range": "error",
"solder_mask_bridge": "error",
"starved_thermal": "warning",
"text_height": "warning",
"text_on_edge_cuts": "error",
"text_thickness": "warning",
"through_hole_pad_without_hole": "error",
"too_many_vias": "error",
"track_angle": "error",
"track_dangling": "warning",
"track_segment_length": "error",
"track_width": "error",
"tracks_crossing": "error",
"unconnected_items": "error",
"unresolved_variable": "error",
"via_dangling": "warning",
"zones_intersect": "error"
},
"rules": {
"max_error": 0.005,
"min_clearance": 0.0,
"min_connection": 0.0,
"min_copper_edge_clearance": 0.5,
"min_groove_width": 0.0,
"min_hole_clearance": 0.15,
"min_hole_to_hole": 0.25,
"min_microvia_diameter": 0.2,
"min_microvia_drill": 0.1,
"min_resolved_spokes": 2,
"min_silk_clearance": 0.0,
"min_text_height": 0.8,
"min_text_thickness": 0.08,
"min_through_hole_diameter": 0.25,
"min_track_width": 0.0,
"min_via_annular_width": 0.05,
"min_via_diameter": 0.25,
"solder_mask_to_copper_clearance": 0.005,
"use_height_for_length_calcs": true
},
"teardrop_options": [
{
"td_onpthpad": true,
"td_onroundshapesonly": false,
"td_onsmdpad": true,
"td_ontrackend": false,
"td_onvia": true
}
],
"teardrop_parameters": [
{
"td_allow_use_two_tracks": true,
"td_curve_segcount": 0,
"td_height_ratio": 1.0,
"td_length_ratio": 0.5,
"td_maxheight": 2.0,
"td_maxlen": 1.0,
"td_on_pad_in_zone": false,
"td_target_name": "td_round_shape",
"td_width_to_size_filter_ratio": 0.9
},
{
"td_allow_use_two_tracks": true,
"td_curve_segcount": 0,
"td_height_ratio": 1.0,
"td_length_ratio": 0.5,
"td_maxheight": 2.0,
"td_maxlen": 1.0,
"td_on_pad_in_zone": false,
"td_target_name": "td_rect_shape",
"td_width_to_size_filter_ratio": 0.9
},
{
"td_allow_use_two_tracks": true,
"td_curve_segcount": 0,
"td_height_ratio": 1.0,
"td_length_ratio": 0.5,
"td_maxheight": 2.0,
"td_maxlen": 1.0,
"td_on_pad_in_zone": false,
"td_target_name": "td_track_end",
"td_width_to_size_filter_ratio": 0.9
}
],
"track_widths": [
0.0,
0.1,
0.2,
0.5
],
"tuning_pattern_settings": {
"diff_pair_defaults": {
"corner_radius_percentage": 80,
"corner_style": 1,
"max_amplitude": 1.0,
"min_amplitude": 0.2,
"single_sided": false,
"spacing": 1.0
},
"diff_pair_skew_defaults": {
"corner_radius_percentage": 80,
"corner_style": 1,
"max_amplitude": 1.0,
"min_amplitude": 0.2,
"single_sided": false,
"spacing": 0.6
},
"single_track_defaults": {
"corner_radius_percentage": 80,
"corner_style": 1,
"max_amplitude": 1.0,
"min_amplitude": 0.2,
"single_sided": false,
"spacing": 0.6
}
},
"via_dimensions": [
{
"diameter": 0.0,
"drill": 0.0
},
{
"diameter": 0.3,
"drill": 0.25
}
],
"zones_allow_external_fillets": false
},
"ipc2581": {
"dist": "",
"distpn": "",
"internal_id": "",
"mfg": "",
"mpn": ""
},
"layer_pairs": [],
"layer_presets": [],
"viewports": []
},
"boards": [],
"cvpcb": {
"equivalence_files": []
},
"erc": {
"erc_exclusions": [],
"meta": {
"version": 0
},
"pin_map": [
[
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
2
],
[
0,
2,
0,
1,
0,
0,
1,
0,
2,
2,
2,
2
],
[
0,
0,
0,
0,
0,
0,
1,
0,
1,
0,
1,
2
],
[
0,
1,
0,
0,
0,
0,
1,
1,
2,
1,
1,
2
],
[
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
2
],
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
2
],
[
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
2
],
[
0,
0,
0,
1,
0,
0,
1,
0,
0,
0,
0,
2
],
[
0,
2,
1,
2,
0,
0,
1,
0,
2,
2,
2,
2
],
[
0,
2,
0,
1,
0,
0,
1,
0,
2,
0,
0,
2
],
[
0,
2,
1,
1,
0,
0,
1,
0,
2,
0,
0,
2
],
[
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2
]
],
"rule_severities": {
"bus_definition_conflict": "error",
"bus_entry_needed": "error",
"bus_to_bus_conflict": "error",
"bus_to_net_conflict": "error",
"different_unit_footprint": "error",
"different_unit_net": "error",
"duplicate_reference": "error",
"duplicate_sheet_names": "error",
"endpoint_off_grid": "warning",
"extra_units": "error",
"footprint_filter": "ignore",
"footprint_link_issues": "warning",
"four_way_junction": "ignore",
"global_label_dangling": "warning",
"hier_label_mismatch": "error",
"label_dangling": "error",
"label_multiple_wires": "warning",
"lib_symbol_issues": "warning",
"lib_symbol_mismatch": "warning",
"missing_bidi_pin": "warning",
"missing_input_pin": "warning",
"missing_power_pin": "error",
"missing_unit": "warning",
"multiple_net_names": "warning",
"net_not_bus_member": "warning",
"no_connect_connected": "warning",
"no_connect_dangling": "warning",
"pin_not_connected": "error",
"pin_not_driven": "error",
"pin_to_pin": "ignore",
"power_pin_not_driven": "ignore",
"same_local_global_label": "warning",
"similar_label_and_power": "warning",
"similar_labels": "warning",
"similar_power": "warning",
"simulation_model_issue": "ignore",
"single_global_label": "ignore",
"unannotated": "error",
"unconnected_wire_endpoint": "warning",
"unit_value_mismatch": "error",
"unresolved_variable": "error",
"wire_dangling": "error"
}
},
"libraries": {
"pinned_footprint_libs": [],
"pinned_symbol_libs": []
},
"meta": {
"filename": "Sensors.kicad_pro",
"version": 3
},
"net_settings": {
"classes": [
{
"bus_width": 12,
"clearance": 0.15,
"diff_pair_gap": 0.25,
"diff_pair_via_gap": 0.25,
"diff_pair_width": 0.2,
"line_style": 0,
"microvia_diameter": 0.3,
"microvia_drill": 0.1,
"name": "Default",
"pcb_color": "rgba(0, 0, 0, 0.000)",
"priority": 2147483647,
"schematic_color": "rgba(0, 0, 0, 0.000)",
"track_width": 0.2,
"via_diameter": 0.6,
"via_drill": 0.3,
"wire_width": 6
}
],
"meta": {
"version": 4
},
"net_colors": null,
"netclass_assignments": null,
"netclass_patterns": []
},
"pcbnew": {
"last_paths": {
"gencad": "",
"idf": "",
"netlist": "",
"plot": "",
"pos_files": "",
"specctra_dsn": "",
"step": "Sensors.step",
"svg": "",
"vrml": ""
},
"page_layout_descr_file": ""
},
"schematic": {
"annotate_start_num": 0,
"bom_export_filename": "${PROJECTNAME}.csv",
"bom_fmt_presets": [],
"bom_fmt_settings": {
"field_delimiter": ",",
"keep_line_breaks": false,
"keep_tabs": false,
"name": "CSV",
"ref_delimiter": ",",
"ref_range_delimiter": "",
"string_delimiter": "\""
},
"bom_presets": [],
"bom_settings": {
"exclude_dnp": false,
"fields_ordered": [
{
"group_by": false,
"label": "Reference",
"name": "Reference",
"show": true
},
{
"group_by": true,
"label": "Value",
"name": "Value",
"show": true
},
{
"group_by": true,
"label": "Footprint",
"name": "Footprint",
"show": true
},
{
"group_by": false,
"label": "Datasheet",
"name": "Datasheet",
"show": true
},
{
"group_by": false,
"label": "Description",
"name": "Description",
"show": false
},
{
"group_by": false,
"label": "Qty",
"name": "${QUANTITY}",
"show": true
},
{
"group_by": false,
"label": "#",
"name": "${ITEM_NUMBER}",
"show": false
},
{
"group_by": false,
"label": "LCSC_PART_NUMBER",
"name": "LCSC_PART_NUMBER",
"show": true
},
{
"group_by": false,
"label": "Sim.Device",
"name": "Sim.Device",
"show": false
},
{
"group_by": false,
"label": "Sim.Pins",
"name": "Sim.Pins",
"show": false
},
{
"group_by": false,
"label": "Sim.Type",
"name": "Sim.Type",
"show": false
},
{
"group_by": true,
"label": "DNP",
"name": "${DNP}",
"show": true
},
{
"group_by": true,
"label": "Exclude from BOM",
"name": "${EXCLUDE_FROM_BOM}",
"show": true
},
{
"group_by": true,
"label": "Exclude from Board",
"name": "${EXCLUDE_FROM_BOARD}",
"show": true
}
],
"filter_string": "",
"group_symbols": true,
"include_excluded_from_bom": true,
"name": "",
"sort_asc": true,
"sort_field": "Reference"
},
"connection_grid_size": 50.0,
"drawing": {
"dashed_lines_dash_length_ratio": 12.0,
"dashed_lines_gap_length_ratio": 3.0,
"default_line_thickness": 6.0,
"default_text_size": 50.0,
"field_names": [],
"intersheets_ref_own_page": false,
"intersheets_ref_prefix": "",
"intersheets_ref_short": false,
"intersheets_ref_show": false,
"intersheets_ref_suffix": "",
"junction_size_choice": 3,
"label_size_ratio": 0.375,
"operating_point_overlay_i_precision": 3,
"operating_point_overlay_i_range": "~A",
"operating_point_overlay_v_precision": 3,
"operating_point_overlay_v_range": "~V",
"overbar_offset_ratio": 1.23,
"pin_symbol_size": 25.0,
"text_offset_ratio": 0.15
},
"legacy_lib_dir": "",
"legacy_lib_list": [],
"meta": {
"version": 1
},
"net_format_name": "",
"page_layout_descr_file": "",
"plot_directory": "",
"space_save_all_events": true,
"spice_current_sheet_as_root": false,
"spice_external_command": "spice \"%I\"",
"spice_model_current_sheet_as_root": true,
"spice_save_all_currents": false,
"spice_save_all_dissipations": false,
"spice_save_all_voltages": false,
"subpart_first_id": 65,
"subpart_id_separator": 0
},
"sheets": [
[
"46346c04-8bed-48b4-837b-9342dd403232",
"Root"
]
],
"text_variables": {}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,4 @@
(sym_lib_table
(version 7)
(lib (name "Modules")(type "KiCad")(uri "/home/empire/workspace/PlantCtrl/board/modules/Modules.kicad_sym")(options "")(descr ""))
)

View File

@@ -0,0 +1,14 @@
[build]
target = "riscv32imc-unknown-none-elf"
[target."riscv32imc-unknown-none-elf"]
rustflags = [
# "-C", "link-arg=-Tlink.x",
]
# runner = "riscv64-unknown-elf-gdb -q -x openocd.gdb"
# runner = "riscv-none-embed-gdb -q -x openocd.gdb"
# runner = "gdb -q -x openocd.gdb"
# runner = "wlink -v flash"
runner = "wlink -v flash --enable-sdi-print --watch-serial --erase"
# runner = "wlink -v flash"

View File

@@ -0,0 +1,7 @@
target extended-remote :3333
set remotetimeout 2000
#symbol-file target/riscv32imc-unknown-none-elf/release/ch32v203-examples
file target/riscv32imc-unknown-none-elf/release/bms
monitor reset halt

View File

@@ -0,0 +1 @@
target

View File

@@ -0,0 +1,43 @@
[package]
name = "bms"
version = "0.1.0"
edition = "2021"
[dependencies]
ch32-hal = { git = "https://github.com/ch32-rs/ch32-hal", features = [
"ch32v203c8t6",
"memory-x",
"embassy",
"rt",
"time-driver-tim2",
], default-features = false }
embassy-executor = { version = "0.7.0", features = [
"arch-riscv32",
"executor-thread",
] }
embassy-time = { version = "0.4.0" }
embassy-usb = { version = "0.3.0" }
embassy-futures = { version = "0.1.0" }
# This is okay because we should automatically use whatever ch32-hal uses
qingke-rt = "*"
qingke = "*"
panic-halt = "1.0"
embedded-hal = "1.0.0"
heapless = "0.8.0"
micromath = { version = "2.1.0", features = ["num-traits"] }
embedded-can = "0.4.1"
[profile.dev]
#lto = true
opt-level = 1
[profile.release]
strip = false # symbols are not flashed to the microcontroller, so don't strip them.
#lto = true
debug = true
opt-level = "z" # Optimize for size.

View File

@@ -0,0 +1,72 @@
# ch32v203-bms
A simple battery management controller software.
## CAN bus and hardware address
This firmware exposes a CAN interface on the CH32V203 and uses 4 hardware address pins to allow up to 16 sensors on the same bus.
- CAN pins (default mapping):
- CAN RX: PA11
- CAN TX: PA12
- Address select pins (with internal pull-ups):
- A0: PA0
- A1: PA1
- A2: PA2
- A3: PA3
Wire each address pin to GND to set its corresponding bit to 1. The 4-bit address range is 0..15. The nodes CAN Standard ID is `0x100 | addr`, i.e. 0x100..0x10F. The CAN acceptance filter is configured to only accept frames with the nodes own ID.
Adjust the pins above if your PCB routes CAN or address lines to different pads.
## 555 timer (software) emulation mode
To save the BOM cost of a classic NE555 in simple oscillator applications, this firmware implements a minimal 555-like Schmitt trigger using the MCUs ADC and a GPIO, approximating the behavior when the capacitor is charged/discharged via Q through a resistor, and the combined Trigger/Threshold senses the capacitor node.
- Pins used:
- Q output: PB2
- Combined Trigger/Threshold (ADC input): PA0
- Wiring:
- PB2 (Q) -> series resistor R -> capacitor node
- Capacitor node -> capacitor to GND
- Capacitor node -> PA0 (ADC input)
- Behavior:
- When ADC(PA0) <= ~1/3 Vref, PB2 is driven High.
- When ADC(PA0) >= ~2/3 Vref, PB2 is driven Low.
- Hysteresis avoids chatter; the actual charge/discharge dynamics follow your chosen R and C.
- Notes:
- Use an appropriate resistor from PB2 to the capacitor to set oscillation frequency. Start with 10k..100k and adjust with C.
- Ensure PA0 is routed to the capacitor node and left high impedance (no strong pull-ups/downs) so the ADC can sense the analog voltage.
- PB2 drives the on-board LED (if present), so the LED might blink at the oscillation frequency.
This mode is implemented in `src/main.rs` using `hal::adc::Adc::convert(&mut pin, SampleTime::...)` to take periodic samples and a simple state machine to toggle the Q output based on ~1/3 and ~2/3 Vref thresholds.
## Building
``` sh
cargo build --release
```
## Flash
``` sh
wchisp config reset
wchip wchisp flash target/riscv32imc-unknown-none-elf/release/bms
```
## Debugging
For debugging purposes a container file is provided together with wrapper scripts to start the containerized `openocd` and `riscv-gdb` transparently. The wrapper scripts assume that `podman` is setup.
Starting Debug server
```
./bin/openocd
```
Connecting with gdb for interactive debugging
```
./bin/gdb -f target/riscv32imc-unknown-none-elf/release/bms
```

View File

@@ -0,0 +1,10 @@
#!/usr/bin/env bash
set -euo pipefail
CONTAINER_NAME="localhost/wch-dev-tools:latest"
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
pushd "$CONTAINER_TOOLS_BASEDIR"
podman build -t "$CONTAINER_NAME" -f "../wch-tools.Containerfile" .
popd

View File

@@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -euo pipefail
CONTAINER_IMAGE="localhost/wch-dev-tools:latest"
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
function _fatal {
echo -e "\e[31mERROR\e[0m $(</dev/stdin)$*" 1>&2
exit 1
}
declare -a PODMAN_ARGS=(
"--rm" "-i" "--log-driver=none"
"--network=host"
"--pid=host"
"-v" "$PWD:$PWD:rw"
"-w" "$PWD"
)
[[ -t 1 ]] && PODMAN_ARGS+=("-t")
if ! podman image exists "$CONTAINER_IMAGE"; then
#attempt to build container
"$CONTAINER_TOOLS_BASEDIR/build-wch-tools-container.sh" 1>&2 ||
_fatal "faild to build local image, cannot continue! … please ensure you have an internet connection"
fi
podman run "${PODMAN_ARGS[@]}" --entrypoint riscv-none-elf-gdb-py3 "$CONTAINER_IMAGE" "$@"

View File

@@ -0,0 +1,44 @@
#!/usr/bin/env bash
set -euo pipefail
CONTAINER_IMAGE="localhost/wch-dev-tools:latest"
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
function _fatal {
echo -e "\e[31mERROR\e[0m $(</dev/stdin)$*" 1>&2
exit 1
}
declare -a PODMAN_ARGS=(
"--rm" "-i" "--log-driver=none"
"--network=host"
"-v" "$PWD:$PWD:rw"
"-w" "$PWD"
)
for device in /dev/bus/usb/*/*; do
if udevadm info "$device" | grep -q "ID_VENDOR=wch.cn" && \
udevadm info "$device" | grep -q "ID_MODEL=WCH-Link"; then
DEBUGGER_DEV_PATH="$device"
break
fi
done
if [[ -z "${DEBUGGER_DEV_PATH:-}" ]]; then
echo "Could not find hardware debugger … Exiting!" 1>&2
exit 1
else
# add jlink to podman device
PODMAN_ARGS+=("--device=$DEBUGGER_DEV_PATH")
fi
[[ -t 1 ]] && PODMAN_ARGS+=("-t")
if ! podman image exists "$CONTAINER_IMAGE"; then
#attempt to build container
"$CONTAINER_TOOLS_BASEDIR/build-wch-tools-container.sh" 1>&2 ||
_fatal "faild to build local image, cannot continue! … please ensure you have an internet connection"
fi
podman run "${PODMAN_ARGS[@]}" --entrypoint openocd "$CONTAINER_IMAGE" "$@"

View File

@@ -0,0 +1,11 @@
fn main() {
// println!("cargo:rustc-link-arg-bins=--nmagic");
println!("cargo:rustc-link-arg-bins=-Tlink.x");
// println!("cargo:rustc-link-arg-bins=-Tdefmt.x");
let out_dir = std::env::var("OUT_DIR").unwrap();
let out_dir = std::path::PathBuf::from(out_dir);
std::fs::write(out_dir.join("memory.x"), include_bytes!("memory.x")).unwrap();
println!("cargo:rustc-link-search={}", out_dir.display());
println!("cargo:rerun-if-changed=memory.x");
}

View File

@@ -0,0 +1,125 @@
/* CH32V203c8t6 */
MEMORY
{
FLASH : ORIGIN = 0x00000000, LENGTH = 64K /* BANK_1 */
RAM : ORIGIN = 0x20000000, LENGTH = 20K
}
REGION_ALIAS("REGION_TEXT", FLASH);
REGION_ALIAS("REGION_RODATA", FLASH);
REGION_ALIAS("REGION_DATA", RAM);
REGION_ALIAS("REGION_BSS", RAM);
REGION_ALIAS("REGION_HEAP", RAM);
REGION_ALIAS("REGION_STACK", RAM);
/* fault handlers */
PROVIDE(InstructionMisaligned = ExceptionHandler);
PROVIDE(InstructionFault = ExceptionHandler);
PROVIDE(IllegalInstruction = ExceptionHandler);
PROVIDE(Breakpoint = ExceptionHandler);
PROVIDE(LoadMisaligned = ExceptionHandler);
PROVIDE(LoadFault = ExceptionHandler);
PROVIDE(StoreMisaligned = ExceptionHandler);
PROVIDE(StoreFault = ExceptionHandler);;
PROVIDE(UserEnvCall = ExceptionHandler);
PROVIDE(SupervisorEnvCall = ExceptionHandler);
PROVIDE(MachineEnvCall = ExceptionHandler);
PROVIDE(InstructionPageFault = ExceptionHandler);
PROVIDE(LoadPageFault = ExceptionHandler);
PROVIDE(StorePageFault = ExceptionHandler);
/* core interrupt handlers */
PROVIDE(NonMaskableInt = DefaultHandler);
PROVIDE(Software = DefaultHandler);
/* external interrupt handlers */
PROVIDE(WWDG = DefaultHandler);
PROVIDE(PVD = DefaultHandler);
PROVIDE(TAMPER = DefaultHandler);
PROVIDE(RTC = DefaultHandler);
PROVIDE(FLASH = DefaultHandler);
PROVIDE(RCC = DefaultHandler);
PROVIDE(EXTI0 = DefaultHandler);
PROVIDE(EXTI1 = DefaultHandler);
PROVIDE(EXTI2 = DefaultHandler);
PROVIDE(EXTI3 = DefaultHandler);
PROVIDE(EXTI4 = DefaultHandler);
PROVIDE(DMA1_CHANNEL1 = DefaultHandler);
PROVIDE(DMA1_CHANNEL2 = DefaultHandler);
PROVIDE(DMA1_CHANNEL3 = DefaultHandler);
PROVIDE(DMA1_CHANNEL4 = DefaultHandler);
PROVIDE(DMA1_CHANNEL5 = DefaultHandler);
PROVIDE(DMA1_CHANNEL6 = DefaultHandler);
PROVIDE(DMA1_CHANNEL7 = DefaultHandler);
PROVIDE(ADC = DefaultHandler);
PROVIDE(USB_HP_CAN1_TX = DefaultHandler);
/*PROVIDE(USB_LP_CAN1_RX0 = DefaultHandler);*/
PROVIDE(CAN1_RX1 = DefaultHandler);
PROVIDE(CAN1_SCE = DefaultHandler);
PROVIDE(EXTI9_5 = DefaultHandler);
PROVIDE(TIM1_BRK = DefaultHandler);
PROVIDE(TIM1_UP_ = DefaultHandler);
PROVIDE(TIM1_TRG_COM = DefaultHandler);
PROVIDE(TIM1_CC = DefaultHandler);
PROVIDE(TIM2 = DefaultHandler);
PROVIDE(TIM3 = DefaultHandler);
PROVIDE(TIM4 = DefaultHandler);
PROVIDE(I2C1_EV = DefaultHandler);
PROVIDE(I2C1_ER = DefaultHandler);
PROVIDE(I2C2_EV = DefaultHandler);
PROVIDE(I2C2_ER = DefaultHandler);
PROVIDE(SPI1 = DefaultHandler);
PROVIDE(SPI2 = DefaultHandler);
PROVIDE(USART1 = DefaultHandler);
PROVIDE(USART2 = DefaultHandler);
PROVIDE(USART3 = DefaultHandler);
PROVIDE(EXTI15_10 = DefaultHandler);
PROVIDE(RTCALARM = DefaultHandler);
PROVIDE(USBWAKE_UP = DefaultHandler);
PROVIDE(TIM8_BRK = DefaultHandler);
PROVIDE(TIM8_UP_ = DefaultHandler);
PROVIDE(TIM8_TRG_COM = DefaultHandler);
PROVIDE(TIM8_CC = DefaultHandler);
PROVIDE(RNG = DefaultHandler);
PROVIDE(FSMC = DefaultHandler);
PROVIDE(SDIO = DefaultHandler);
PROVIDE(TIM5 = DefaultHandler);
PROVIDE(SPI3 = DefaultHandler);
PROVIDE(UART4 = DefaultHandler);
PROVIDE(UART5 = DefaultHandler);
PROVIDE(TIM6 = DefaultHandler);
PROVIDE(TIM7 = DefaultHandler);
PROVIDE(DMA2_CHANNEL1 = DefaultHandler);
PROVIDE(DMA2_CHANNEL2 = DefaultHandler);
PROVIDE(DMA2_CHANNEL3 = DefaultHandler);
PROVIDE(DMA2_CHANNEL4 = DefaultHandler);
PROVIDE(DMA2_CHANNEL5 = DefaultHandler);
PROVIDE(ETH = DefaultHandler);
PROVIDE(ETH_WKUP = DefaultHandler);
PROVIDE(CAN2_TX = DefaultHandler);
PROVIDE(CAN2_RX0 = DefaultHandler);
PROVIDE(CAN2_RX1 = DefaultHandler);
PROVIDE(CAN2_SCE = DefaultHandler);
PROVIDE(OTG_FS = DefaultHandler);
PROVIDE(USBHSWAKEUP = DefaultHandler);
PROVIDE(USBHS = DefaultHandler);
PROVIDE(DVP = DefaultHandler);
PROVIDE(UART6 = DefaultHandler);
PROVIDE(UART7 = DefaultHandler);
PROVIDE(UART8 = DefaultHandler);
PROVIDE(TIM9_BRK = DefaultHandler);
PROVIDE(TIM9_UP_ = DefaultHandler);
PROVIDE(TIM9_TRG_COM = DefaultHandler);
PROVIDE(TIM9_CC = DefaultHandler);
PROVIDE(TIM10_BRK = DefaultHandler);
PROVIDE(TIM10_UP_ = DefaultHandler);
PROVIDE(TIM10_TRG_COM = DefaultHandler);
PROVIDE(TIM10_CC = DefaultHandler);
PROVIDE(DMA2_CHANNEL6 = DefaultHandler);
PROVIDE(DMA2_CHANNEL7 = DefaultHandler);
PROVIDE(DMA2_CHANNEL8 = DefaultHandler);
PROVIDE(DMA2_CHANNEL9 = DefaultHandler);
PROVIDE(DMA2_CHANNEL10 = DefaultHandler);
PROVIDE(DMA2_CHANNEL11 = DefaultHandler);

View File

@@ -0,0 +1,17 @@
set _CHIPNAME ch32v203
set _TARGETNAME $_CHIPNAME.cpu
#bindto 0.0.0.0
adapter driver wlinke
adapter speed 6000
transport select sdi
sdi newtap $_CHIPNAME cpu -irlen 5 --expected-id 0x00001
target create $_TARGETNAME.0 wch_riscv -chain-position $_TARGETNAME
$_TARGETNAME.0 configure -work-area-phys 0x20000000 -work-area-size 10000 -work-area-backup 1
set _FLASHNAME $_CHIPNAME.flash
flash bank $_FLASHNAME wch_rsicv 0x00000000 0 0 0 $_TARGETNAME.0
init

View File

@@ -0,0 +1,2 @@
[toolchain]
channel = "nightly"

View File

@@ -0,0 +1,61 @@
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
#![feature(impl_trait_in_assoc_type)]
// Simple 555-like oscillator implemented in firmware.
// - Q output: PB2 (also drives the on-board LED if present)
// - Combined Trigger/Threshold analog input: PA0 (capacitor node)
// Wiring suggestion:
// Q (PB2) --[R]--+-- C -- GND
// |
// PA0 (ADC input)
// The firmware toggles Q high when PA0 <= 1/3 Vref and low when PA0 >= 2/3 Vref.
use embassy_executor::Spawner;
use embassy_time::Timer;
use hal::gpio::{Level, Output};
use {ch32_hal as hal, panic_halt as _};
use hal::adc::{Adc, SampleTime};
#[embassy_executor::main(entry = "qingke_rt::entry")]
async fn main(_spawner: Spawner) -> ! {
let p = hal::init(Default::default());
// Q output on PB2
let mut q = Output::new(p.PB2, Level::Low, Default::default());
// ADC on PA0 for combined Trigger/Threshold input
let mut adc = Adc::new(p.ADC1, Default::default());
let mut trig_thres = p.PA0; // analog-capable pin used as ADC channel
// ADC characteristics: assume 12-bit if HAL doesn't expose it.
// If the HAL provides a method to query resolution, prefer that.
let full_scale: u16 = 4095; // 12-bit default
let thr_low: u16 = (full_scale as u32 / 3) as u16; // ~1/3 Vref
let thr_high: u16 = ((full_scale as u32 * 2) / 3) as u16; // ~2/3 Vref
// Start with Q low. State variable to avoid redundant toggles.
let mut q_high = false;
q.set_low();
loop {
// Read capacitor node voltage via ADC
let sample: u16 = adc.convert(&mut trig_thres, SampleTime::CYCLES239_5);
// Implement Schmitt trigger behavior like NE555 using thresholds
if !q_high && sample <= thr_low {
// Trigger: voltage fell below 1/3 Vref -> set output high
q.set_high();
q_high = true;
} else if q_high && sample >= thr_high {
// Threshold: voltage rose above 2/3 Vref -> set output low
q.set_low();
q_high = false;
}
// Small delay to reduce CPU usage; adjust for responsiveness/noise
Timer::after_micros(200).await;
}
}

View File

@@ -0,0 +1,27 @@
FROM debian:bookworm
RUN apt update -y && apt upgrade -y && apt install git libjaylink-dev libusb-1.0-0 unzip curl libhidapi-hidraw0 xz-utils -y
RUN cd /root && \
curl -L -o mrs-toolchain.tar.xz "https://github.com/ch32-riscv-ug/MounRiver_Studio_Community_miror/releases/download/1.92-toolchain/MRS_Toolchain_Linux_x64_V1.92.tar.xz" && \
mkdir mrs-toolchain && \
tar -xvf mrs-toolchain.tar.xz -C mrs-toolchain --strip-components=1 && \
mv mrs-toolchain/OpenOCD/bin/openocd /usr/local/bin && \
mv mrs-toolchain/OpenOCD/share/openocd /usr/local/share && \
# mv mrs-toolchain/RISC-V_Embedded_GCC12/bin/riscv-none-elf-gdb /usr/local/bin && \ # both toolchains in MRS are to old to work with emacs dape
# mv mrs-toolchain/RISC-V_Embedded_GCC12/libexec /usr/local && \ # both toolchains in MRS are to old to work with emacs dape
rm -rf mrs-toolchain mrs-toolchain.tar.xz && \
# Use up to date xpack toolchains for gdb
curl -L -o xpack-riscv-toolchain.tar.gz "https://github.com/xpack-dev-tools/riscv-none-elf-gcc-xpack/releases/download/v14.2.0-3/xpack-riscv-none-elf-gcc-14.2.0-3-linux-x64.tar.gz" && \
mkdir xpack-toolchain && \
tar -xvf xpack-riscv-toolchain.tar.gz -C xpack-toolchain --strip-components=1 && \
mv xpack-toolchain/bin/* /usr/local/bin && \
mv xpack-toolchain/lib/ /usr/local && \
mv xpack-toolchain/lib64/ /usr/local && \
mv xpack-toolchain/libexec /usr/local && \
mv xpack-toolchain/riscv-none-elf /usr/local && \
rm -rf xpack-toolchain xpack-riscv-toolchain.tar.gz
RUN mkdir -p /root/.config/gdb && echo "set auto-load safe-path /" >> /root/.config/gdb/gdbinit
ENTRYPOINT [ "/usr/bin/bash" ]

View File

@@ -460,6 +460,7 @@
"single_global_label": "ignore",
"unannotated": "error",
"unconnected_wire_endpoint": "warning",
"undefined_netclass": "error",
"unit_value_mismatch": "error",
"unresolved_variable": "error",
"wire_dangling": "error"

View File

@@ -0,0 +1,4 @@
(fp_lib_table
(version 7)
(lib (name "Sensor")(type "KiCad")(uri "${KIPRJMOD}/Sensor.pretty")(options "")(descr ""))
)

BIN
case/PlantCtrl Case v9.f3z Normal file

Binary file not shown.

View File

@@ -1,26 +1,29 @@
[build]
#target = "xtensa-esp32-espidf"
target = "riscv32imac-esp-espidf"
rustflags = [
# Required to obtain backtraces (e.g. when using the "esp-backtrace" crate.)
# NOTE: May negatively impact performance of produced code
"-C", "force-frame-pointers",
"-Z", "stack-protector=all",
"-C", "link-arg=-Tlinkall.x",
]
[target.riscv32imac-esp-espidf]
linker = "ldproxy"
target = "riscv32imac-unknown-none-elf"
[target.riscv32imac-unknown-none-elf]
runner = "espflash flash --monitor --chip esp32c6 --baud 921600 --partition-table partitions.csv"
#runner = "espflash flash --monitor --baud 921600 --partition-table partitions.csv -b no-reset" # Select this runner in case of usb ttl
runner = "espflash flash --monitor"
#runner = "espflash flash --monitor"
#runner = "cargo runner"
#runner = "espflash flash --monitor --partition-table partitions.csv -b no-reset" # create upgrade image file for webupload
# runner = espflash erase-parts otadata //ensure flash is clean
rustflags = ["--cfg", "espidf_time64"] # Extending time_t for ESP IDF 5: https://github.com/esp-rs/rust/issues/110
[unstable]
build-std = ["std", "panic_abort"]
[env]
MCU = "esp32c6"
# Note: this variable is not used by the pio builder (`cargo build --features pio`)
ESP_IDF_VERSION = "v5.2.1"
CHRONO_TZ_TIMEZONE_FILTER = "UTC|America/New_York|America/Chicago|America/Los_Angeles|Europe/London|Europe/Berlin|Europe/Paris|Asia/Tokyo|Asia/Shanghai|Asia/Kolkata|Australia/Sydney|America/Sao_Paulo|Africa/Johannesburg|Asia/Dubai|Pacific/Auckland"
CARGO_WORKSPACE_DIR = { value = "", relative = true }
RUST_BACKTRACE = "full"
ESP_LOG = "info"
[unstable]
build-std = ["alloc", "core"]

View File

@@ -1,21 +1,17 @@
[package]
name = "plant-ctrl2"
version = "0.1.0"
authors = ["Empire Phoenix"]
edition = "2021"
resolver = "2"
#rust-version = "1.71"
[profile.dev]
# Explicitly disable LTO which the Xtensa codegen backend has issues
lto = false
strip = false
debug = true
overflow-checks = true
panic = "abort"
incremental = true
opt-level = 2
name = "plant-ctrl2"
rust-version = "1.86"
version = "0.1.0"
# Explicitly configure the binary target and disable building it as a test/bench.
[[bin]]
name = "plant-ctrl2"
path = "src/main.rs"
# Prevent IDEs/Cargo from trying to compile a test harness for this no_std binary.
test = false
bench = false
doc = false
[package.metadata.cargo_runner]
# The string `$TARGET_FILE` will be replaced with the path from cargo.
@@ -30,74 +26,140 @@ command = [
"partitions.csv"
]
[profile.dev]
lto = true
strip = false
debug = false
overflow-checks = true
panic = "abort"
incremental = true
opt-level = 3
[profile.release]
# Explicitly disable LTO which the Xtensa codegen backend has issues
lto = true
strip = true
debug = false
overflow-checks = true
panic = "abort"
incremental = true
opt-level = 3
[package.metadata.espflash]
partition_table = "partitions.csv"
[features]
default = ["std", "esp-idf-svc/native"]
pio = ["esp-idf-svc/pio"]
std = ["alloc", "esp-idf-svc/binstart", "esp-idf-svc/std"]
alloc = ["esp-idf-svc/alloc"]
nightly = ["esp-idf-svc/nightly"]
experimental = ["esp-idf-svc/experimental"]
#embassy = ["esp-idf-svc/embassy-sync", "esp-idf-svc/critical-section", "esp-idf-svc/embassy-time-driver"]
[dependencies]
#ESP stuff
embedded-svc = { version = "0.28.1", features = ["experimental"] }
esp-idf-hal = "0.45.2"
esp-idf-sys = { version = "0.36.1", features = ["binstart", "native"] }
esp-idf-svc = { version = "0.51.0", default-features = false }
esp-bootloader-esp-idf = { version = "0.2.0", features = ["esp32c6"] }
esp-hal = { version = "=1.0.0-rc.0", features = [
"esp32c6",
"log-04",
"unstable",
"rt"
] }
log = "0.4.27"
embassy-net = { version = "0.7.0", features = [
"dhcpv4",
"log",
"medium-ethernet",
"tcp",
"udp",
] }
embedded-io = "0.6.1"
embedded-io-async = "0.6.1"
esp-alloc = "0.8.0"
esp-backtrace = { version = "0.17.0", features = [
"esp32c6",
"exception-handler",
"panic-handler",
"println",
"colors",
"custom-halt"
] }
esp-println = { version = "0.15.0", features = ["esp32c6", "log-04"] }
# for more networking protocol support see https://crates.io/crates/edge-net
embassy-executor = { version = "0.7.0", features = [
"log",
"task-arena-size-131072"
] }
embassy-time = { version = "0.5.0", features = ["log"] }
esp-hal-embassy = { version = "0.9.0", features = ["esp32c6", "log-04"] }
esp-storage = { version = "0.7.0", features = ["esp32c6"] }
esp-wifi = { version = "0.15.0", features = [
"builtin-scheduler",
"esp-alloc",
"esp32c6",
"log-04",
"smoltcp",
"wifi",
] }
smoltcp = { version = "0.12.0", default-features = false, features = [
"alloc",
"log",
"medium-ethernet",
"multicast",
"proto-dhcpv4",
"proto-dns",
"proto-ipv4",
"socket-dns",
"socket-icmp",
"socket-raw",
"socket-tcp",
"socket-udp",
] }
#static_cell = "2.1.1"
embedded-hal = "1.0.0"
heapless = { version = "0.8", features = ["serde"] }
embedded-hal-bus = { version = "0.3.0", features = ["std"] }
embedded-hal-bus = { version = "0.3.0" }
#Hardware additional driver
ds18b20 = "0.1.1"
bq34z100 = { version = "0.3.0", features = ["flashstream"] }
#ds18b20 = "0.1.1"
#bq34z100 = { version = "0.3.0", default-features = false }
one-wire-bus = "0.1.1"
ds323x = "0.6.0"
#pure code dependencies
once_cell = "1.19.0"
anyhow = { version = "1.0.75", features = ["std", "backtrace"] }
strum = { version = "0.27.0", features = ["derive"] }
#once_cell = "1.19.0"
anyhow = { version = "1.0.75", default-features = false }
#strum = { version = "0.27.0", default-feature = false, features = ["derive"] }
measurements = "0.11.0"
#json
serde = { version = "1.0.192", features = ["derive"] }
serde_json = "1.0.108"
serde = { version = "1.0.219", features = ["derive", "alloc"], default-features = false }
serde_json = { version = "1.0.143", default-features = false, features = ["alloc"] }
#timezone
chrono = { version = "0.4.23", default-features = false, features = ["iana-time-zone", "alloc", "serde"] }
chrono-tz = { version = "0.10.3", default-features = false, features = ["filter-by-regex"] }
chrono = { version = "0.4.42", default-features = false, features = ["iana-time-zone", "alloc", "serde"] }
chrono-tz = { version = "0.10.4", default-features = false, features = ["filter-by-regex"] }
eeprom24x = "0.7.2"
url = "2.5.3"
crc = "3.2.1"
bincode = "2.0.1"
ringbuffer = "0.15.0"
text-template = "0.1.0"
strum_macros = "0.27.0"
esp-ota = { version = "0.2.2", features = ["log"] }
unit-enum = "1.4.1"
pca9535 = { version = "2.0.0", features = ["std"] }
ina219 = { version = "0.2.0", features = ["std"] }
pca9535 = { version = "2.0.0" }
ina219 = { version = "0.2.0" }
embedded-storage = "=0.3.1"
ekv = "1.0.0"
embedded-can = "0.4.1"
portable-atomic = "1.11.1"
embassy-sync = { version = "0.7.2", features = ["log"] }
async-trait = "0.1.89"
bq34z100 = { version = "0.4.0", default-features = false }
edge-dhcp = "0.6.0"
edge-nal = "0.5.0"
edge-nal-embassy = "0.6.0"
static_cell = "2.1.1"
edge-http = { version = "0.6.1", features = ["log"] }
littlefs2 = { version = "0.6.1", features = ["c-stubs", "alloc"] }
littlefs2-core = "0.1.1"
bytemuck = { version = "1.23.2", features = ["derive", "min_const_generics", "pod_saturating", "extern_crate_alloc"] }
[patch.crates-io]
#esp-idf-hal = { git = "https://github.com/esp-rs/esp-idf-hal.git" }
#esp-idf-hal = { git = "https://github.com/empirephoenix/esp-idf-hal.git" }
#esp-idf-sys = { git = "https://github.com/empirephoenix/esp-idf-sys.git" }
#esp-idf-sys = { git = "https://github.com/esp-rs/esp-idf-sys.git" }
#esp-idf-svc = { git = "https://github.com/esp-rs/esp-idf-svc.git" }
#bq34z100 = { path = "../../bq34z100_rust" }
[build-dependencies]
cc = "=1.1.30"
embuild = { version = "0.32.0", features = ["espidf"] }
vergen = { version = "8.2.6", features = ["build", "git", "gitcl"] }

View File

@@ -1,8 +1,62 @@
use std::process::Command;
use vergen::EmitBuilder;
fn linker_be_nice() {
let args: Vec<String> = std::env::args().collect();
if args.len() > 1 {
let kind = &args[1];
let what = &args[2];
match kind.as_str() {
"undefined-symbol" => match what.as_str() {
"_defmt_timestamp" => {
eprintln!();
eprintln!("💡 `defmt` not found - make sure `defmt.x` is added as a linker script and you have included `use defmt_rtt as _;`");
eprintln!();
}
"_stack_start" => {
eprintln!();
eprintln!("💡 Is the linker script `linkall.x` missing?");
eprintln!();
}
"esp_wifi_preempt_enable"
| "esp_wifi_preempt_yield_task"
| "esp_wifi_preempt_task_create" => {
eprintln!();
eprintln!("💡 `esp-wifi` has no scheduler enabled. Make sure you have the `builtin-scheduler` feature enabled, or that you provide an external scheduler.");
eprintln!();
}
"embedded_test_linker_file_not_added_to_rustflags" => {
eprintln!();
eprintln!("💡 `embedded-test` not found - make sure `embedded-test.x` is added as a linker script for tests");
eprintln!();
}
_ => (),
},
// we don't have anything helpful for "missing-lib" yet
_ => {
std::process::exit(1);
}
}
std::process::exit(0);
}
println!(
"cargo:rustc-link-arg=--error-handling-script={}",
std::env::current_exe().unwrap().display()
);
}
fn main() {
println!("cargo:rerun-if-changed=./src/src_webpack");
webpack();
linker_be_nice();
let _ = EmitBuilder::builder().all_git().all_build().emit();
}
fn webpack() {
//println!("cargo:rerun-if-changed=./src/src_webpack");
Command::new("rm")
.arg("./src/webserver/bundle.js")
.output()
@@ -64,7 +118,4 @@ fn main() {
.unwrap();
}
}
embuild::espidf::sysenv::output();
let _ = EmitBuilder::builder().all_git().all_build().emit();
}

View File

@@ -1,5 +1,8 @@
partition_table = "partitions.csv"
[connection]
serial = "/dev/ttyACM0"
[[usb_device]]
vid = "303a"
pid = "1001"
[flash]
size = "16MB"
size = "16MB"

View File

@@ -3,4 +3,4 @@ otadata, data, ota, , 8k,
phy_init, data, phy, , 4k,
ota_0, app, ota_0, , 3968k,
ota_1, app, ota_1, , 3968k,
storage, data, spiffs, , 8M,
storage, data, littlefs,, 8M,
1 nvs data nvs 16k
3 phy_init data phy 4k
4 ota_0 app ota_0 3968k
5 ota_1 app ota_1 3968k
6 storage data spiffs littlefs 8M

View File

@@ -10,14 +10,12 @@ use crate::{
};
use anyhow::{bail, Ok, Result};
use embedded_hal::digital::OutputPin;
use esp_idf_hal::{
gpio::{AnyInputPin, IOPin, InputOutput, PinDriver, Pull},
pcnt::{PcntChannel, PcntChannelConfig, PcntControlMode, PcntCountMode, PcntDriver, PinIndex},
};
use esp_idf_sys::{gpio_hold_dis, gpio_hold_en};
use measurements::{Current, Voltage};
use plant_ctrl2::sipo::ShiftRegister40;
use std::result::Result::Ok as OkStd;
use core::result::Result::Ok as OkStd;
use alloc::string::ToString;
use alloc::boxed::Box;
use esp_hall::gpio::Pull;
const PUMP8_BIT: usize = 0;
const PUMP1_BIT: usize = 1;
@@ -94,7 +92,7 @@ pub(crate) fn create_v3(
battery_monitor: Box<dyn BatteryInteraction + Send>,
rtc_module: Box<dyn RTCModuleInteraction + Send>,
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
println!("Start v3");
log::info!("Start v3");
let mut clock = PinDriver::input_output(peripherals.gpio15.downgrade())?;
clock.set_pull(Pull::Floating)?;
let mut latch = PinDriver::input_output(peripherals.gpio3.downgrade())?;
@@ -136,7 +134,7 @@ pub(crate) fn create_v3(
peripherals.gpio5,
tank_power_pin,
flow_sensor_pin,
peripherals.pcnt1
peripherals.pcnt1,
)?;
let mut signal_counter = PcntDriver::new(
@@ -210,7 +208,7 @@ impl<'a> BoardInteraction<'a> for V3<'a> {
&self.config
}
fn get_battery_monitor(&mut self) -> &mut Box<(dyn BatteryInteraction + Send + 'static)> {
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send + 'static> {
&mut self.battery_monitor
}

View File

@@ -12,24 +12,18 @@ use crate::log::{log, LogMessage};
use anyhow::bail;
use embedded_hal::digital::OutputPin;
use embedded_hal_bus::i2c::MutexDevice;
use esp_idf_hal::gpio::{AnyInputPin, IOPin, InputOutput, Output, PinDriver, Pull};
use esp_idf_hal::i2c::{I2cDriver, I2cError};
use esp_idf_hal::pcnt::{
PcntChannel, PcntChannelConfig, PcntControlMode, PcntCountMode, PcntDriver, PinIndex,
};
use esp_idf_sys::{gpio_hold_dis, gpio_hold_en};
use ina219::address::{Address, Pin};
use ina219::calibration::UnCalibrated;
use ina219::configuration::{Configuration, OperatingMode};
use ina219::SyncIna219;
use measurements::{Current, Resistance, Voltage};
use pca9535::{ExpanderError, GPIOBank, Pca9535Immediate, StandardExpanderInterface};
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
use std::result::Result::Ok as OkStd;
use embedded_can::nb::Can;
use embedded_can::Frame;
use embedded_can::StandardId;
use esp_idf_hal::prelude::*;
use esp_idf_hal::can;
use alloc::string::ToString;
use alloc::boxed::Box;
use esp_hal::gpio::Pull;
pub enum Charger<'a> {
SolarMpptV1 {
@@ -54,7 +48,7 @@ impl Charger<'_> {
operating_mode: OperatingMode::PowerDown,
})
.map_err(|e| {
println!(
log::info!(
"Error setting ina mppt configuration during deep sleep preparation{:?}",
e
);
@@ -135,7 +129,7 @@ pub(crate) fn create_v4(
battery_monitor: Box<dyn BatteryInteraction + Send>,
rtc_module: Box<dyn RTCModuleInteraction + Send>,
) -> anyhow::Result<Box<dyn BoardInteraction<'static> + Send + 'static>> {
println!("Start v4");
log::info!("Start v4");
let mut awake = PinDriver::output(peripherals.gpio21.downgrade())?;
awake.set_high()?;
@@ -159,13 +153,13 @@ pub(crate) fn create_v4(
peripherals.gpio5,
tank_power_pin,
flow_sensor_pin,
peripherals.pcnt1
peripherals.pcnt1,
)?;
let mut sensor_expander = Pca9535Immediate::new(MutexDevice::new(&I2C_DRIVER), 34);
let sensor = match sensor_expander.pin_into_output(GPIOBank::Bank0, 0) {
Ok(_) => {
println!("SensorExpander answered");
log::info!("SensorExpander answered");
//pulse counter version
let mut signal_counter = PcntDriver::new(
peripherals.pcnt0,
@@ -202,10 +196,10 @@ pub(crate) fn create_v4(
}
}
Err(_) => {
println!("Can bus mode ");
log::info!("Can bus mode ");
let timing = can::config::Timing::B25K;
let config = can::config::Config::new().timing(timing);
let mut can = can::CanDriver::new(peripherals.can, peripherals.gpio0, peripherals.gpio2, &config).unwrap();
let can = can::CanDriver::new(peripherals.can, peripherals.gpio0, peripherals.gpio2, &config).unwrap();
let frame = StandardId::new(0x042).unwrap();
@@ -213,7 +207,7 @@ pub(crate) fn create_v4(
can.transmit(&tx_frame, 1000).unwrap();
if let Ok(rx_frame) = can.receive(1000) {
println!("rx {:}:", rx_frame);
log::info!("rx {:}:", rx_frame);
}
//can bus version
SensorImpl::CanBus {
@@ -276,7 +270,7 @@ pub(crate) fn create_v4(
) {
Ok(pump_ina) => Some(pump_ina),
Err(err) => {
println!("Error creating pump ina: {:?}", err);
log::info!("Error creating pump ina: {:?}", err);
None
}
};

View File

@@ -1,16 +1,17 @@
use crate::hal::Sensor;
use crate::log::{log, LogMessage};
use alloc::string::ToString;
use embedded_hal_bus::i2c::MutexDevice;
use esp_idf_hal::can::CanDriver;
use esp_idf_hal::delay::Delay;
use esp_idf_hal::i2c::I2cDriver;
use esp_idf_hal::pcnt::PcntDriver;
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
use crate::hal::Sensor;
use crate::log::{log, LogMessage};
const REPEAT_MOIST_MEASURE: usize = 10;
pub trait SensorInteraction {
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32>;
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32>;
}
const MS0: u8 = 1_u8;
@@ -21,19 +22,23 @@ const MS4: u8 = 2_u8;
const SENSOR_ON: u8 = 5_u8;
pub enum SensorImpl<'a> {
PulseCounter{
PulseCounter {
signal_counter: PcntDriver<'a>,
sensor_expander: Pca9535Immediate<MutexDevice<'a, I2cDriver<'a>>>,
},
CanBus{
can: CanDriver<'a>
}
CanBus {
can: CanDriver<'a>,
},
}
impl SensorInteraction for SensorImpl<'_> {
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32> {
match self {
SensorImpl::PulseCounter { signal_counter, sensor_expander, .. } => {
SensorImpl::PulseCounter {
signal_counter,
sensor_expander,
..
} => {
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
for repeat in 0..REPEAT_MOIST_MEASURE {
signal_counter.counter_pause()?;
@@ -70,8 +75,7 @@ impl SensorInteraction for SensorImpl<'_> {
}
sensor_expander.pin_set_low(GPIOBank::Bank0, MS4)?;
sensor_expander
.pin_set_high(GPIOBank::Bank0, SENSOR_ON)?;
sensor_expander.pin_set_high(GPIOBank::Bank0, SENSOR_ON)?;
let delay = Delay::new_default();
let measurement = 100; // TODO what is this scaling factor? what is its purpose?
@@ -83,8 +87,7 @@ impl SensorInteraction for SensorImpl<'_> {
delay.delay_ms(measurement);
signal_counter.counter_pause()?;
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
sensor_expander
.pin_set_low(GPIOBank::Bank0, SENSOR_ON)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, SENSOR_ON)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;

176
rust/scratch/water.rs Normal file
View File

@@ -0,0 +1,176 @@
use crate::hal::TANK_MULTI_SAMPLE;
use anyhow::{anyhow, bail};
use ds18b20::Ds18b20;
use esp_idf_hal::adc::oneshot::config::AdcChannelConfig;
use esp_idf_hal::adc::oneshot::{AdcChannelDriver, AdcDriver};
use esp_idf_hal::adc::{attenuation, Resolution, ADC1};
use esp_idf_hal::delay::Delay;
use esp_idf_hal::gpio::{AnyIOPin, AnyInputPin, Gpio5, InputOutput, PinDriver, Pull};
use esp_idf_hal::pcnt::{
PcntChannel, PcntChannelConfig, PcntControlMode, PcntCountMode, PcntDriver, PinIndex, PCNT1,
};
use esp_idf_sys::EspError;
use one_wire_bus::OneWire;
pub struct TankSensor<'a> {
// one_wire_bus: OneWire<PinDriver<'a, AnyIOPin, InputOutput>>,
// tank_channel: AdcChannelDriver<'a, Gpio5, AdcDriver<'a, ADC1>>,
// tank_power: PinDriver<'a, AnyIOPin, InputOutput>,
// flow_counter: PcntDriver<'a>,
// delay: Delay,
}
impl<'a> TankSensor<'a> {
pub(crate) fn create(
// one_wire_pin: AnyIOPin,
// adc1: ADC1,
// gpio5: Gpio5,
// tank_power_pin: AnyIOPin,
// flow_sensor_pin: AnyIOPin,
// pcnt1: PCNT1,
) -> anyhow::Result<TankSensor<'a>> {
// let mut one_wire_pin =
// PinDriver::input_output_od(one_wire_pin).expect("Failed to configure pin");
// one_wire_pin
// .set_pull(Pull::Floating)
// .expect("Failed to set pull");
//
// let adc_config = AdcChannelConfig {
// attenuation: attenuation::DB_11,
// resolution: Resolution::Resolution12Bit,
// calibration: esp_idf_hal::adc::oneshot::config::Calibration::Curve,
// };
// let tank_driver = AdcDriver::new(adc1).expect("Failed to configure ADC");
// let tank_channel = AdcChannelDriver::new(tank_driver, gpio5, &adc_config)
// .expect("Failed to configure ADC channel");
//
// let mut tank_power =
// PinDriver::input_output(tank_power_pin).expect("Failed to configure pin");
// tank_power
// .set_pull(Pull::Floating)
// .expect("Failed to set pull");
//
// let one_wire_bus =
// OneWire::new(one_wire_pin).expect("OneWire bus did not pull up after release");
//
// let mut flow_counter = PcntDriver::new(
// pcnt1,
// Some(flow_sensor_pin),
// Option::<AnyInputPin>::None,
// Option::<AnyInputPin>::None,
// Option::<AnyInputPin>::None,
// )?;
//
// flow_counter.channel_config(
// PcntChannel::Channel1,
// PinIndex::Pin0,
// PinIndex::Pin1,
// &PcntChannelConfig {
// lctrl_mode: PcntControlMode::Keep,
// hctrl_mode: PcntControlMode::Keep,
// pos_mode: PcntCountMode::Increment,
// neg_mode: PcntCountMode::Hold,
// counter_h_lim: i16::MAX,
// counter_l_lim: 0,
// },
// )?;
//
// Ok(TankSensor {
// one_wire_bus,
// tank_channel,
// tank_power,
// flow_counter,
// delay: Default::default(),
// })
bail!("Tank sensor not implemented");
}
pub fn reset_flow_meter(&mut self) {
// self.flow_counter.counter_pause().unwrap();
// self.flow_counter.counter_clear().unwrap();
}
pub fn start_flow_meter(&mut self) {
//self.flow_counter.counter_resume().unwrap();
}
pub fn get_flow_meter_value(&mut self) -> i16 {
//self.flow_counter.get_counter_value().unwrap()
5_i16
}
pub fn stop_flow_meter(&mut self) -> i16 {
//self.flow_counter.counter_pause().unwrap();
self.get_flow_meter_value()
}
pub async fn water_temperature_c(&mut self) -> anyhow::Result<f32> {
//multisample should be moved to water_temperature_c
let mut attempt = 1;
let water_temp: Result<f32, anyhow::Error> = loop {
let temp = self.single_temperature_c().await;
match &temp {
Ok(res) => {
log::info!("Water temp is {}", res);
break temp;
}
Err(err) => {
log::info!("Could not get water temp {} attempt {}", err, attempt)
}
}
if attempt == 5 {
break temp;
}
attempt += 1;
};
water_temp
}
async fn single_temperature_c(&mut self) -> anyhow::Result<f32> {
bail!("err");
// self.one_wire_bus
// .reset(&mut self.delay)
// .map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
// let first = self.one_wire_bus.devices(false, &mut self.delay).next();
// if first.is_none() {
// bail!("Not found any one wire Ds18b20");
// }
// let device_address = first
// .unwrap()
// .map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
// let water_temp_sensor = Ds18b20::new::<EspError>(device_address)
// .map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
//
// water_temp_sensor
// .start_temp_measurement(&mut self.one_wire_bus, &mut self.delay)
// .map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
// ds18b20::Resolution::Bits12.delay_for_measurement_time(&mut self.delay);
// let sensor_data = water_temp_sensor
// .read_data(&mut self.one_wire_bus, &mut self.delay)
// .map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
// if sensor_data.temperature == 85_f32 {
// bail!("Ds18b20 dummy temperature returned");
// }
//anyhow::Ok(sensor_data.temperature / 10_f32)
Ok(13_f32)
}
pub async fn tank_sensor_voltage(&mut self) -> anyhow::Result<f32> {
// self.tank_power.set_high()?;
// //let stabilize
// self.delay.delay_ms(100);
//
// let mut store = [0_u16; TANK_MULTI_SAMPLE];
// for multisample in 0..TANK_MULTI_SAMPLE {
// let value = self.tank_channel.read()?;
// store[multisample] = value;
// }
// self.tank_power.set_low()?;
//
// store.sort();
// let median_mv = store[6] as f32 / 1000_f32;
let median_mv = 10_f32;
anyhow::Ok(median_mv)
}
}

View File

@@ -1,7 +1,8 @@
use alloc::string::String;
use core::str::FromStr;
use crate::hal::PLANT_COUNT;
use crate::plant_state::PlantWateringMode;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(default)]
@@ -11,6 +12,8 @@ pub struct NetworkConfig {
pub password: Option<heapless::String<64>>,
pub mqtt_url: Option<heapless::String<128>>,
pub base_topic: Option<heapless::String<64>>,
pub mqtt_user: Option<heapless::String<32>>,
pub mqtt_password: Option<heapless::String<64>>,
pub max_wait: u32,
}
impl Default for NetworkConfig {
@@ -21,6 +24,8 @@ impl Default for NetworkConfig {
password: None,
mqtt_url: None,
base_topic: None,
mqtt_user: None,
mqtt_password: None,
max_wait: 10000,
}
}
@@ -58,7 +63,7 @@ pub struct TankConfig {
pub tank_warn_percent: u8,
pub tank_empty_percent: u8,
pub tank_full_percent: u8,
pub ml_per_pulse: f32
pub ml_per_pulse: f32,
}
impl Default for TankConfig {
fn default() -> Self {
@@ -111,6 +116,7 @@ pub struct PlantControllerConfig {
pub struct PlantConfig {
pub mode: PlantWateringMode,
pub target_moisture: f32,
pub min_moisture: f32,
pub pump_time_s: u16,
pub pump_limit_ml: u16,
pub pump_cooldown_min: u16,
@@ -131,6 +137,7 @@ impl Default for PlantConfig {
Self {
mode: PlantWateringMode::OFF,
target_moisture: 40.,
min_moisture: 30.,
pump_time_s: 30,
pump_limit_ml: 5000,
pump_cooldown_min: 60,

View File

@@ -1,22 +1,27 @@
use anyhow::anyhow;
use bq34z100::{Bq34Z100Error, Bq34z100g1, Bq34z100g1Driver};
use embedded_hal_bus::i2c::MutexDevice;
use esp_idf_hal::delay::Delay;
use esp_idf_hal::i2c::{I2cDriver, I2cError};
use measurements::Temperature;
use crate::hal::Box;
use alloc::string::String;
use async_trait::async_trait;
use core::error::Error;
use serde::Serialize;
#[async_trait]
pub trait BatteryInteraction {
fn state_charge_percent(&mut self) -> Result<f32, BatteryError>;
fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError>;
fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError>;
fn cycle_count(&mut self) -> Result<u16, BatteryError>;
fn state_health_percent(&mut self) -> Result<u16, BatteryError>;
fn bat_temperature(&mut self) -> Result<u16, BatteryError>;
fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError>;
async fn state_charge_percent(&mut self) -> Result<f32, BatteryError>;
async fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
async fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
async fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
async fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError>;
async fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError>;
async fn cycle_count(&mut self) -> Result<u16, BatteryError>;
async fn state_health_percent(&mut self) -> Result<u16, BatteryError>;
async fn bat_temperature(&mut self) -> Result<u16, BatteryError>;
async fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError>;
}
impl From<BatteryError> for anyhow::Error {
fn from(err: BatteryError) -> Self {
anyhow::anyhow!(err)
}
}
#[derive(Debug, Serialize)]
@@ -37,13 +42,13 @@ pub enum BatteryError {
CommunicationError(String),
}
impl From<Bq34Z100Error<esp_idf_hal::i2c::I2cError>> for BatteryError {
fn from(err: Bq34Z100Error<esp_idf_hal::i2c::I2cError>) -> Self {
BatteryError::CommunicationError(
anyhow!("failed to communicate with battery monitor: {:?}", err).to_string(),
)
}
}
// impl From<Bq34Z100Error<esp_idf_hal::i2c::I2cError>> for BatteryError {
// fn from(err: Bq34Z100Error<esp_idf_hal::i2c::I2cError>) -> Self {
// BatteryError::CommunicationError(
// anyhow!("failed to communicate with battery monitor: {:?}", err).to_string(),
// )
// }
// }
#[derive(Debug, Serialize)]
pub enum BatteryState {
@@ -53,45 +58,45 @@ pub enum BatteryState {
/// If no battery monitor is installed this implementation will be used
pub struct NoBatteryMonitor {}
#[async_trait]
impl BatteryInteraction for NoBatteryMonitor {
fn state_charge_percent(&mut self) -> Result<f32, BatteryError> {
async fn state_charge_percent(&mut self) -> Result<f32, BatteryError> {
Err(BatteryError::NoBatteryMonitor)
}
fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
async fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
Err(BatteryError::NoBatteryMonitor)
}
fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
async fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
Err(BatteryError::NoBatteryMonitor)
}
fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
async fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
Err(BatteryError::NoBatteryMonitor)
}
fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError> {
async fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError> {
Err(BatteryError::NoBatteryMonitor)
}
fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError> {
async fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError> {
Err(BatteryError::NoBatteryMonitor)
}
fn cycle_count(&mut self) -> Result<u16, BatteryError> {
async fn cycle_count(&mut self) -> Result<u16, BatteryError> {
Err(BatteryError::NoBatteryMonitor)
}
fn state_health_percent(&mut self) -> Result<u16, BatteryError> {
async fn state_health_percent(&mut self) -> Result<u16, BatteryError> {
Err(BatteryError::NoBatteryMonitor)
}
fn bat_temperature(&mut self) -> Result<u16, BatteryError> {
async fn bat_temperature(&mut self) -> Result<u16, BatteryError> {
Err(BatteryError::NoBatteryMonitor)
}
fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError> {
async fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError> {
Ok(BatteryState::Unknown)
}
}
@@ -100,115 +105,115 @@ impl BatteryInteraction for NoBatteryMonitor {
#[allow(dead_code)]
pub struct WchI2cSlave {}
pub struct BQ34Z100G1<'a> {
pub battery_driver: Bq34z100g1Driver<MutexDevice<'a, I2cDriver<'a>>, Delay>,
}
impl BatteryInteraction for BQ34Z100G1<'_> {
fn state_charge_percent(&mut self) -> Result<f32, BatteryError> {
Ok(self.battery_driver.state_of_charge().map(f32::from)?)
}
fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
Ok(self.battery_driver.remaining_capacity()?)
}
fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
Ok(self.battery_driver.full_charge_capacity()?)
}
fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
Ok(self.battery_driver.design_capacity()?)
}
fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError> {
Ok(self.battery_driver.voltage()?)
}
fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError> {
Ok(self.battery_driver.average_current()?)
}
fn cycle_count(&mut self) -> Result<u16, BatteryError> {
Ok(self.battery_driver.cycle_count()?)
}
fn state_health_percent(&mut self) -> Result<u16, BatteryError> {
Ok(self.battery_driver.state_of_health()?)
}
fn bat_temperature(&mut self) -> Result<u16, BatteryError> {
Ok(self.battery_driver.temperature()?)
}
fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError> {
Ok(BatteryState::Info(BatteryInfo {
voltage_milli_volt: self.voltage_milli_volt()?,
average_current_milli_ampere: self.average_current_milli_ampere()?,
cycle_count: self.cycle_count()?,
design_milli_ampere_hour: self.design_milli_ampere_hour()?,
remaining_milli_ampere_hour: self.remaining_milli_ampere_hour()?,
state_of_charge: self.state_charge_percent()?,
state_of_health: self.state_health_percent()?,
temperature: self.bat_temperature()?,
}))
}
}
pub fn print_battery_bq34z100(
battery_driver: &mut Bq34z100g1Driver<MutexDevice<I2cDriver<'_>>, Delay>,
) -> anyhow::Result<(), Bq34Z100Error<I2cError>> {
println!("Try communicating with battery");
let fwversion = battery_driver.fw_version().unwrap_or_else(|e| {
println!("Firmware {:?}", e);
0
});
println!("fw version is {}", fwversion);
let design_capacity = battery_driver.design_capacity().unwrap_or_else(|e| {
println!("Design capacity {:?}", e);
0
});
println!("Design Capacity {}", design_capacity);
if design_capacity == 1000 {
println!("Still stock configuring battery, readouts are likely to be wrong!");
}
let flags = battery_driver.get_flags_decoded()?;
println!("Flags {:?}", flags);
let chem_id = battery_driver.chem_id().unwrap_or_else(|e| {
println!("Chemid {:?}", e);
0
});
let bat_temp = battery_driver.internal_temperature().unwrap_or_else(|e| {
println!("Bat Temp {:?}", e);
0
});
let temp_c = Temperature::from_kelvin(bat_temp as f64 / 10_f64).as_celsius();
let voltage = battery_driver.voltage().unwrap_or_else(|e| {
println!("Bat volt {:?}", e);
0
});
let current = battery_driver.current().unwrap_or_else(|e| {
println!("Bat current {:?}", e);
0
});
let state = battery_driver.state_of_charge().unwrap_or_else(|e| {
println!("Bat Soc {:?}", e);
0
});
let charge_voltage = battery_driver.charge_voltage().unwrap_or_else(|e| {
println!("Bat Charge Volt {:?}", e);
0
});
let charge_current = battery_driver.charge_current().unwrap_or_else(|e| {
println!("Bat Charge Current {:?}", e);
0
});
println!("ChemId: {} Current voltage {} and current {} with charge {}% and temp {} CVolt: {} CCur {}", chem_id, voltage, current, state, temp_c, charge_voltage, charge_current);
let _ = battery_driver.unsealed();
let _ = battery_driver.it_enable();
anyhow::Result::Ok(())
}
// pub struct BQ34Z100G1<'a> {
// pub battery_driver: Bq34z100g1Driver<MutexDevice<'a, I2cDriver<'a>>, Delay>,
// }
//
// impl BatteryInteraction for BQ34Z100G1<'_> {
// fn state_charge_percent(&mut self) -> Result<f32, BatteryError> {
// Ok(self.battery_driver.state_of_charge().map(f32::from)?)
// }
//
// fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
// Ok(self.battery_driver.remaining_capacity()?)
// }
//
// fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
// Ok(self.battery_driver.full_charge_capacity()?)
// }
//
// fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
// Ok(self.battery_driver.design_capacity()?)
// }
//
// fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError> {
// Ok(self.battery_driver.voltage()?)
// }
//
// fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError> {
// Ok(self.battery_driver.average_current()?)
// }
//
// fn cycle_count(&mut self) -> Result<u16, BatteryError> {
// Ok(self.battery_driver.cycle_count()?)
// }
//
// fn state_health_percent(&mut self) -> Result<u16, BatteryError> {
// Ok(self.battery_driver.state_of_health()?)
// }
//
// fn bat_temperature(&mut self) -> Result<u16, BatteryError> {
// Ok(self.battery_driver.temperature()?)
// }
//
// fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError> {
// Ok(BatteryState::Info(BatteryInfo {
// voltage_milli_volt: self.voltage_milli_volt()?,
// average_current_milli_ampere: self.average_current_milli_ampere()?,
// cycle_count: self.cycle_count()?,
// design_milli_ampere_hour: self.design_milli_ampere_hour()?,
// remaining_milli_ampere_hour: self.remaining_milli_ampere_hour()?,
// state_of_charge: self.state_charge_percent()?,
// state_of_health: self.state_health_percent()?,
// temperature: self.bat_temperature()?,
// }))
// }
// }
//
// pub fn print_battery_bq34z100(
// battery_driver: &mut Bq34z100g1Driver<MutexDevice<I2cDriver<'_>>, Delay>,
// ) -> anyhow::Result<(), Bq34Z100Error<I2cError>> {
// log::info!("Try communicating with battery");
// let fwversion = battery_driver.fw_version().unwrap_or_else(|e| {
// log::info!("Firmware {:?}", e);
// 0
// });
// log::info!("fw version is {}", fwversion);
//
// let design_capacity = battery_driver.design_capacity().unwrap_or_else(|e| {
// log::info!("Design capacity {:?}", e);
// 0
// });
// log::info!("Design Capacity {}", design_capacity);
// if design_capacity == 1000 {
// log::info!("Still stock configuring battery, readouts are likely to be wrong!");
// }
//
// let flags = battery_driver.get_flags_decoded()?;
// log::info!("Flags {:?}", flags);
//
// let chem_id = battery_driver.chem_id().unwrap_or_else(|e| {
// log::info!("Chemid {:?}", e);
// 0
// });
//
// let bat_temp = battery_driver.internal_temperature().unwrap_or_else(|e| {
// log::info!("Bat Temp {:?}", e);
// 0
// });
// let temp_c = Temperature::from_kelvin(bat_temp as f64 / 10_f64).as_celsius();
// let voltage = battery_driver.voltage().unwrap_or_else(|e| {
// log::info!("Bat volt {:?}", e);
// 0
// });
// let current = battery_driver.current().unwrap_or_else(|e| {
// log::info!("Bat current {:?}", e);
// 0
// });
// let state = battery_driver.state_of_charge().unwrap_or_else(|e| {
// log::info!("Bat Soc {:?}", e);
// 0
// });
// let charge_voltage = battery_driver.charge_voltage().unwrap_or_else(|e| {
// log::info!("Bat Charge Volt {:?}", e);
// 0
// });
// let charge_current = battery_driver.charge_current().unwrap_or_else(|e| {
// log::info!("Bat Charge Current {:?}", e);
// 0
// });
// log::info!("ChemId: {} Current voltage {} and current {} with charge {}% and temp {} CVolt: {} CCur {}", chem_id, voltage, current, state, temp_c, charge_voltage, charge_current);
// let _ = battery_driver.unsealed();
// let _ = battery_driver.it_enable();
// anyhow::Result::Ok(())
// }

File diff suppressed because it is too large Load Diff

View File

@@ -1,20 +1,22 @@
use crate::hal::esp::Esp;
use crate::hal::rtc::{BackupHeader, RTCModuleInteraction};
use crate::hal::water::TankSensor;
use crate::hal::{deep_sleep, BoardInteraction, FreePeripherals, Sensor};
use alloc::vec::Vec;
//use crate::hal::water::TankSensor;
use crate::alloc::boxed::Box;
use crate::hal::{BoardInteraction, FreePeripherals, Sensor};
use crate::{
config::PlantControllerConfig,
hal::battery::{BatteryInteraction, NoBatteryMonitor},
};
use anyhow::{bail, Result};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use embedded_hal::digital::OutputPin;
use esp_idf_hal::gpio::{IOPin, Pull};
use esp_idf_hal::gpio::{InputOutput, PinDriver};
use esp_hal::gpio::{Level, Output, OutputConfig};
use log::info;
use measurements::{Current, Voltage};
pub struct Initial<'a> {
pub(crate) general_fault: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
pub(crate) general_fault: Output<'a>,
pub(crate) esp: Esp<'a>,
pub(crate) config: PlantControllerConfig,
pub(crate) battery: Box<dyn BatteryInteraction + Send>,
@@ -23,42 +25,36 @@ pub struct Initial<'a> {
struct NoRTC {}
#[async_trait]
impl RTCModuleInteraction for NoRTC {
fn get_backup_info(&mut self) -> Result<BackupHeader> {
async fn get_backup_info(&mut self) -> Result<BackupHeader> {
bail!("Please configure board revision")
}
fn get_backup_config(&mut self) -> Result<Vec<u8>> {
async fn get_backup_config(&mut self) -> Result<Vec<u8>> {
bail!("Please configure board revision")
}
fn backup_config(&mut self, _bytes: &[u8]) -> Result<()> {
async fn backup_config(&mut self, _bytes: &[u8]) -> Result<()> {
bail!("Please configure board revision")
}
fn get_rtc_time(&mut self) -> Result<DateTime<Utc>> {
async fn get_rtc_time(&mut self) -> Result<DateTime<Utc>> {
bail!("Please configure board revision")
}
fn set_rtc_time(&mut self, _time: &DateTime<Utc>) -> Result<()> {
async fn set_rtc_time(&mut self, _time: &DateTime<Utc>) -> Result<()> {
bail!("Please configure board revision")
}
}
pub(crate) fn create_initial_board(
free_pins: FreePeripherals,
fs_mount_error: bool,
free_pins: FreePeripherals<'static>,
config: PlantControllerConfig,
esp: Esp<'static>,
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
println!("Start initial");
let mut general_fault = PinDriver::input_output(free_pins.gpio6.downgrade())?;
general_fault.set_pull(Pull::Floating)?;
general_fault.set_low()?;
if fs_mount_error {
general_fault.set_high()?
}
log::info!("Start initial");
let general_fault = Output::new(free_pins.gpio23, Level::Low, OutputConfig::default());
let v = Initial {
general_fault,
config,
@@ -69,10 +65,11 @@ pub(crate) fn create_initial_board(
Ok(Box::new(v))
}
#[async_trait]
impl<'a> BoardInteraction<'a> for Initial<'a> {
fn get_tank_sensor(&mut self) -> Option<&mut TankSensor<'a>> {
None
}
// fn get_tank_sensor(&mut self) -> Option<&mut TankSensor<'a>> {
// None
// }
fn get_esp(&mut self) -> &mut Esp<'a> {
&mut self.esp
@@ -94,8 +91,8 @@ impl<'a> BoardInteraction<'a> for Initial<'a> {
bail!("Please configure board revision")
}
fn deep_sleep(&mut self, duration_in_ms: u64) -> ! {
deep_sleep(duration_in_ms)
async fn deep_sleep(&mut self, duration_in_ms: u64) -> ! {
self.esp.deep_sleep(duration_in_ms).await;
}
fn is_day(&self) -> bool {
false
@@ -104,41 +101,39 @@ impl<'a> BoardInteraction<'a> for Initial<'a> {
bail!("Please configure board revision")
}
fn pump(&mut self, _plant: usize, _enable: bool) -> Result<()> {
async fn pump(&mut self, _plant: usize, _enable: bool) -> Result<()> {
bail!("Please configure board revision")
}
fn pump_current(&mut self, _plant: usize) -> Result<Current> {
async fn pump_current(&mut self, _plant: usize) -> Result<Current> {
bail!("Please configure board revision")
}
fn fault(&mut self, _plant: usize, _enable: bool) -> Result<()> {
async fn fault(&mut self, _plant: usize, _enable: bool) -> Result<()> {
bail!("Please configure board revision")
}
fn measure_moisture_hz(&mut self, _plant: usize, _sensor: Sensor) -> Result<f32> {
async fn measure_moisture_hz(&mut self, _plant: usize, _sensor: Sensor) -> Result<f32> {
bail!("Please configure board revision")
}
fn general_fault(&mut self, enable: bool) {
let _ = self.general_fault.set_state(enable.into());
async fn general_fault(&mut self, enable: bool) {
self.general_fault.set_level(enable.into());
}
fn test(&mut self) -> Result<()> {
async fn test(&mut self) -> Result<()> {
bail!("Please configure board revision")
}
fn set_config(&mut self, config: PlantControllerConfig) -> anyhow::Result<()> {
fn set_config(&mut self, config: PlantControllerConfig) {
self.config = config;
self.esp.save_config(&self.config)?;
anyhow::Ok(())
}
fn get_mptt_voltage(&mut self) -> Result<Voltage> {
async fn get_mptt_voltage(&mut self) -> Result<Voltage> {
bail!("Please configure board revision")
}
fn get_mptt_current(&mut self) -> Result<Current> {
async fn get_mptt_current(&mut self) -> Result<Current> {
bail!("Please configure board revision")
}
}

View File

@@ -0,0 +1,73 @@
use embedded_storage::{ReadStorage, Storage};
use esp_bootloader_esp_idf::partitions::FlashRegion;
use esp_storage::FlashStorage;
use littlefs2::consts::U512 as lfsCache;
use littlefs2::consts::U512 as lfsLookahead;
use littlefs2::driver::Storage as lfs2Storage;
use littlefs2::fs::Filesystem as lfs2Filesystem;
use littlefs2::io::Error as lfs2Error;
use littlefs2::io::Result as lfs2Result;
use log::{error, info};
pub struct LittleFs2Filesystem {
pub(crate) storage: &'static mut FlashRegion<'static, FlashStorage>,
}
impl lfs2Storage for LittleFs2Filesystem {
const READ_SIZE: usize = 256;
const WRITE_SIZE: usize = 512;
const BLOCK_SIZE: usize = 512; //usually optimal for flash access
const BLOCK_COUNT: usize = 8 * 1024 * 1024 / 512; //8mb in 32kb blocks
const BLOCK_CYCLES: isize = 100;
type CACHE_SIZE = lfsCache;
type LOOKAHEAD_SIZE = lfsLookahead;
fn read(&mut self, off: usize, buf: &mut [u8]) -> lfs2Result<usize> {
let read_size: usize = Self::READ_SIZE;
assert_eq!(off % read_size, 0);
assert_eq!(buf.len() % read_size, 0);
match self.storage.read(off as u32, buf) {
anyhow::Result::Ok(..) => lfs2Result::Ok(buf.len()),
Err(err) => {
error!("Littlefs2Filesystem read error: {:?}", err);
Err(lfs2Error::IO)
}
}
}
fn write(&mut self, off: usize, data: &[u8]) -> lfs2Result<usize> {
info!(
"Littlefs2Filesystem write at offset {} with len {}",
off,
data.len()
);
let write_size: usize = Self::WRITE_SIZE;
assert_eq!(off % write_size, 0);
assert_eq!(data.len() % write_size, 0);
match self.storage.write(off as u32, data) {
anyhow::Result::Ok(..) => lfs2Result::Ok(data.len()),
Err(err) => {
error!("Littlefs2Filesystem write error: {:?}", err);
Err(lfs2Error::IO)
}
}
}
fn erase(&mut self, off: usize, len: usize) -> lfs2Result<usize> {
info!(
"Littlefs2Filesystem erase at offset {} with len {}",
off, len
);
let block_size: usize = Self::BLOCK_SIZE;
debug_assert!(off % block_size == 0);
debug_assert!(len % block_size == 0);
//match self.storage.erase(off as u32, len as u32) {
//anyhow::Result::Ok(..) => lfs2Result::Ok(len),
//Err(err) => {
//error!("Littlefs2Filesystem erase error: {:?}", err);
//Err(lfs2Error::IO)
// }
//}
lfs2Result::Ok(len)
}
}

View File

@@ -1,81 +1,68 @@
pub(crate) mod battery;
mod esp;
pub mod esp;
mod initial_hal;
mod little_fs2storage_adapter;
mod rtc;
mod v3_hal;
mod v4_hal;
mod water;
mod v4_sensor;
//mod water;
use crate::hal::rtc::{DS3231Module, RTCModuleInteraction};
use crate::hal::water::TankSensor;
use crate::alloc::string::ToString;
use crate::hal::rtc::RTCModuleInteraction;
use esp_hal::peripherals::Peripherals;
use esp_hal::peripherals::GPIO23;
use esp_hal::peripherals::GPIO6;
//use crate::hal::water::TankSensor;
use crate::{
config::{BatteryBoardVersion, BoardVersion, PlantControllerConfig},
hal::{
battery::{print_battery_bq34z100, BatteryInteraction, NoBatteryMonitor},
battery::{BatteryInteraction, NoBatteryMonitor},
esp::Esp,
},
log::{log, LogMessage},
log::{LogMessage},
};
use anyhow::{Ok, Result};
use battery::BQ34Z100G1;
use bq34z100::Bq34z100g1Driver;
use ds323x::{DateTimeAccess, Ds323x};
use eeprom24x::{Eeprom24x, SlaveAddr, Storage};
use embedded_hal_bus::i2c::MutexDevice;
use esp_idf_hal::{
adc::ADC1,
delay::Delay,
gpio::{
Gpio0, Gpio1, Gpio10, Gpio11, Gpio12, Gpio13, Gpio14, Gpio15, Gpio16, Gpio17, Gpio18,
Gpio2, Gpio21, Gpio22, Gpio23, Gpio24, Gpio25, Gpio26, Gpio27, Gpio28, Gpio29, Gpio3,
Gpio30, Gpio4, Gpio5, Gpio6, Gpio7, Gpio8, IOPin, PinDriver, Pull,
},
i2c::{APBTickType, I2cConfig, I2cDriver},
pcnt::PCNT0,
prelude::Peripherals,
reset::ResetReason,
units::FromValueType,
use alloc::boxed::Box;
use alloc::format;
use alloc::sync::Arc;
use core::cell::OnceCell;
use anyhow::{bail, Ok, Result};
use async_trait::async_trait;
use chrono::{DateTime, FixedOffset, Utc};
use embassy_executor::Spawner;
//use battery::BQ34Z100G1;
//use bq34z100::Bq34z100g1Driver;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use esp_bootloader_esp_idf::partitions::{
AppPartitionSubType, DataPartitionSubType, FlashRegion, PartitionEntry,
};
use esp_idf_svc::{eventloop::EspSystemEventLoop, nvs::EspDefaultNvsPartition, wifi::EspWifi};
use esp_idf_sys::{
esp_deep_sleep, esp_restart, esp_sleep_enable_ext1_wakeup,
esp_sleep_ext1_wakeup_mode_t_ESP_EXT1_WAKEUP_ANY_LOW,
};
use esp_ota::mark_app_valid;
use esp_hal::clock::CpuClock;
use esp_hal::gpio::{Input, InputConfig, Pull};
use measurements::{Current, Voltage};
use once_cell::sync::Lazy;
use std::result::Result::Ok as OkStd;
use std::sync::Mutex;
use std::time::Duration;
use esp_idf_hal::can::CAN;
use esp_idf_hal::pcnt::PCNT1;
use crate::hal::little_fs2storage_adapter::LittleFs2Filesystem;
use embassy_sync::mutex::Mutex;
use embassy_sync::once_lock::OnceLock;
use esp_alloc as _;
use esp_backtrace as _;
use esp_bootloader_esp_idf::ota::Slot;
use esp_hal::rng::Rng;
use esp_hal::rtc_cntl::{Rtc, SocResetReason};
use esp_hal::system::reset_reason;
use esp_hal::timer::timg::TimerGroup;
use esp_storage::FlashStorage;
use esp_wifi::{init, EspWifiController};
use littlefs2::fs::{Allocation, Filesystem as lfs2Filesystem};
use littlefs2::object_safe::DynStorage;
use log::{info, warn};
use crate::log::{LogArray, LOG_ACCESS};
pub static TIME_ACCESS: OnceLock<Rtc> = OnceLock::new();
//Only support for 8 right now!
pub const PLANT_COUNT: usize = 8;
const TANK_MULTI_SAMPLE: usize = 11;
pub static I2C_DRIVER: Lazy<Mutex<I2cDriver<'static>>> = Lazy::new(PlantHal::create_i2c);
fn deep_sleep(duration_in_ms: u64) -> ! {
unsafe {
//if we don't do this here, we might just revert newly flashed firmware
mark_app_valid();
//allow early wakeup by pressing the boot button
if duration_in_ms == 0 {
esp_restart();
} else {
//configure gpio 1 to wakeup on low, reused boot button for this
esp_sleep_enable_ext1_wakeup(
0b10u64,
esp_sleep_ext1_wakeup_mode_t_ESP_EXT1_WAKEUP_ANY_LOW,
);
esp_deep_sleep(duration_in_ms);
}
};
}
//pub static I2C_DRIVER: LazyLock<Mutex<CriticalSectionRawMutex,I2cDriver<'static>>> = LazyLock::new(PlantHal::create_i2c);
#[derive(Debug, PartialEq)]
pub enum Sensor {
@@ -89,266 +76,446 @@ pub struct HAL<'a> {
pub board_hal: Box<dyn BoardInteraction<'a> + Send>,
}
#[async_trait]
pub trait BoardInteraction<'a> {
fn get_tank_sensor(&mut self) -> Option<&mut TankSensor<'a>>;
//fn get_tank_sensor(&mut self) -> Option<&mut TankSensor>;
fn get_esp(&mut self) -> &mut Esp<'a>;
fn get_config(&mut self) -> &PlantControllerConfig;
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send>;
fn get_rtc_module(&mut self) -> &mut Box<dyn RTCModuleInteraction + Send>;
fn set_charge_indicator(&mut self, charging: bool) -> Result<()>;
fn deep_sleep(&mut self, duration_in_ms: u64) -> !;
async fn deep_sleep(&mut self, duration_in_ms: u64) -> !;
fn is_day(&self) -> bool;
//should be multsampled
fn light(&mut self, enable: bool) -> Result<()>;
fn pump(&mut self, plant: usize, enable: bool) -> Result<()>;
fn pump_current(&mut self, plant: usize) -> Result<Current>;
fn fault(&mut self, plant: usize, enable: bool) -> Result<()>;
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32>;
fn general_fault(&mut self, enable: bool);
fn test(&mut self) -> Result<()>;
fn set_config(&mut self, config: PlantControllerConfig) -> Result<()>;
fn get_mptt_voltage(&mut self) -> anyhow::Result<Voltage>;
fn get_mptt_current(&mut self) -> anyhow::Result<Current>;
async fn pump(&mut self, plant: usize, enable: bool) -> Result<()>;
async fn pump_current(&mut self, plant: usize) -> Result<Current>;
async fn fault(&mut self, plant: usize, enable: bool) -> Result<()>;
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32>;
async fn general_fault(&mut self, enable: bool);
async fn test(&mut self) -> Result<()>;
fn set_config(&mut self, config: PlantControllerConfig);
async fn get_mptt_voltage(&mut self) -> anyhow::Result<Voltage>;
async fn get_mptt_current(&mut self) -> anyhow::Result<Current>;
}
impl dyn BoardInteraction<'_> {
//the counter is just some arbitrary number that increases whenever some progress was made, try to keep the updates < 10 per second for ux reasons
fn progress(&mut self, counter: u32) {
async fn _progress(&mut self, counter: u32) {
let even = counter % 2 == 0;
let current = counter / (PLANT_COUNT as u32);
for led in 0..PLANT_COUNT {
self.fault(led, current == led as u32).unwrap();
match self.fault(led, current == led as u32).await {
Result::Ok(_) => {}
Err(err) => {
warn!("Fault on plant {}: {:?}", led, err);
}
}
}
let _ = self.general_fault(even.into());
}
}
#[allow(dead_code)]
pub struct FreePeripherals {
pub gpio0: Gpio0,
pub gpio1: Gpio1,
pub gpio2: Gpio2,
pub gpio3: Gpio3,
pub gpio4: Gpio4,
pub gpio5: Gpio5,
pub gpio6: Gpio6,
pub gpio7: Gpio7,
pub gpio8: Gpio8,
//config button here
pub gpio10: Gpio10,
pub gpio11: Gpio11,
pub gpio12: Gpio12,
pub gpio13: Gpio13,
pub gpio14: Gpio14,
pub gpio15: Gpio15,
pub gpio16: Gpio16,
pub gpio17: Gpio17,
pub gpio18: Gpio18,
//i2c here
pub gpio21: Gpio21,
pub gpio22: Gpio22,
pub gpio23: Gpio23,
pub gpio24: Gpio24,
pub gpio25: Gpio25,
pub gpio26: Gpio26,
pub gpio27: Gpio27,
pub gpio28: Gpio28,
pub gpio29: Gpio29,
pub gpio30: Gpio30,
pub pcnt0: PCNT0,
pub pcnt1: PCNT1,
pub adc1: ADC1,
pub can: CAN,
pub struct FreePeripherals<'a> {
// pub gpio0: Gpio0,
// pub gpio1: Gpio1,
// pub gpio2: Gpio2,
// pub gpio3: Gpio3,
// pub gpio4: Gpio4,
// pub gpio5: Gpio5,
pub gpio6: GPIO6<'a>,
// pub gpio7: Gpio7,
// pub gpio8: Gpio8,
// //config button here
// pub gpio10: Gpio10,
// pub gpio11: Gpio11,
// pub gpio12: Gpio12,
// pub gpio13: Gpio13,
// pub gpio14: Gpio14,
// pub gpio15: Gpio15,
// pub gpio16: Gpio16,
// pub gpio17: Gpio17,
// pub gpio18: Gpio18,
// //i2c here
// pub gpio21: Gpio21,
// pub gpio22: Gpio22,
pub gpio23: GPIO23<'a>,
// pub gpio24: Gpio24,
// pub gpio25: Gpio25,
// pub gpio26: Gpio26,
// pub gpio27: Gpio27,
// pub gpio28: Gpio28,
// pub gpio29: Gpio29,
// pub gpio30: Gpio30,
// pub pcnt0: PCNT0,
// pub pcnt1: PCNT1,
// pub adc1: ADC1,
// pub can: CAN,
}
macro_rules! mk_static {
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
const GW_IP_ADDR_ENV: Option<&'static str> = option_env!("GATEWAY_IP");
impl PlantHal {
fn create_i2c() -> Mutex<I2cDriver<'static>> {
let peripherals = unsafe { Peripherals::new() };
// fn create_i2c() -> Mutex<CriticalSectionRawMutex, I2cDriver<'static>> {
// let peripherals = unsafe { Peripherals::new() };
//
// let config = I2cConfig::new()
// .scl_enable_pullup(true)
// .sda_enable_pullup(true)
// .baudrate(100_u32.kHz().into())
// .timeout(APBTickType::from(Duration::from_millis(100)));
//
// let i2c = peripherals.i2c0;
// let scl = peripherals.pins.gpio19.downgrade();
// let sda = peripherals.pins.gpio20.downgrade();
//
// Mutex::new(I2cDriver::new(i2c, sda, scl, &config).unwrap())
// }
let config = I2cConfig::new()
.scl_enable_pullup(true)
.sda_enable_pullup(true)
.baudrate(100_u32.kHz().into())
.timeout(APBTickType::from(Duration::from_millis(100)));
pub async fn create(spawner: Spawner) -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>> {
let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
let peripherals: Peripherals = esp_hal::init(config);
let i2c = peripherals.i2c0;
let scl = peripherals.pins.gpio19.downgrade();
let sda = peripherals.pins.gpio20.downgrade();
esp_alloc::heap_allocator!(size: 64 * 1024);
esp_alloc::heap_allocator!(#[link_section = ".dram2_uninit"] size: 64000);
Mutex::new(I2cDriver::new(i2c, sda, scl, &config).unwrap())
}
let rtc: Rtc = Rtc::new(peripherals.LPWR);
match(TIME_ACCESS.init(rtc)){
Result::Ok(_) => {}
Err(_) => {}
}
pub fn create() -> Result<Mutex<HAL<'static>>> {
let peripherals = Peripherals::take()?;
let sys_loop = EspSystemEventLoop::take()?;
let nvs = EspDefaultNvsPartition::take()?;
let wifi_driver = EspWifi::new(peripherals.modem, sys_loop, Some(nvs))?;
let systimer = SystemTimer::new(peripherals.SYSTIMER);
let mut boot_button = PinDriver::input(peripherals.pins.gpio9.downgrade())?;
boot_button.set_pull(Pull::Floating)?;
let boot_button = Input::new(
peripherals.GPIO9,
InputConfig::default().with_pull(Pull::None),
);
let rng = Rng::new(peripherals.RNG);
let timg0 = TimerGroup::new(peripherals.TIMG0);
let esp_wifi_ctrl = &*mk_static!(
EspWifiController<'static>,
init(timg0.timer0, rng.clone()).expect("Could not init wifi controller")
);
let (controller, interfaces) =
esp_wifi::wifi::new(&esp_wifi_ctrl, peripherals.WIFI).expect("Could not init wifi");
use esp_hal::timer::systimer::SystemTimer;
esp_hal_embassy::init(systimer.alarm0);
//let mut adc1 = Adc::new(peripherals.ADC1, adc1_config);
//
let free_pins = FreePeripherals {
can: peripherals.can,
adc1: peripherals.adc1,
pcnt0: peripherals.pcnt0,
pcnt1: peripherals.pcnt1,
gpio0: peripherals.pins.gpio0,
gpio1: peripherals.pins.gpio1,
gpio2: peripherals.pins.gpio2,
gpio3: peripherals.pins.gpio3,
gpio4: peripherals.pins.gpio4,
gpio5: peripherals.pins.gpio5,
gpio6: peripherals.pins.gpio6,
gpio7: peripherals.pins.gpio7,
gpio8: peripherals.pins.gpio8,
gpio10: peripherals.pins.gpio10,
gpio11: peripherals.pins.gpio11,
gpio12: peripherals.pins.gpio12,
gpio13: peripherals.pins.gpio13,
gpio14: peripherals.pins.gpio14,
gpio15: peripherals.pins.gpio15,
gpio16: peripherals.pins.gpio16,
gpio17: peripherals.pins.gpio17,
gpio18: peripherals.pins.gpio18,
gpio21: peripherals.pins.gpio21,
gpio22: peripherals.pins.gpio22,
gpio23: peripherals.pins.gpio23,
gpio24: peripherals.pins.gpio24,
gpio25: peripherals.pins.gpio25,
gpio26: peripherals.pins.gpio26,
gpio27: peripherals.pins.gpio27,
gpio28: peripherals.pins.gpio28,
gpio29: peripherals.pins.gpio29,
gpio30: peripherals.pins.gpio30,
// can: peripherals.can,
// adc1: peripherals.adc1,
// pcnt0: peripherals.pcnt0,
// pcnt1: peripherals.pcnt1,
// gpio0: peripherals.pins.gpio0,
// gpio1: peripherals.pins.gpio1,
// gpio2: peripherals.pins.gpio2,
// gpio3: peripherals.pins.gpio3,
// gpio4: peripherals.pins.gpio4,
// gpio5: peripherals.pins.gpio5,
gpio6: peripherals.GPIO6,
// gpio7: peripherals.pins.gpio7,
// gpio8: peripherals.pins.gpio8,
// gpio10: peripherals.pins.gpio10,
// gpio11: peripherals.pins.gpio11,
// gpio12: peripherals.pins.gpio12,
// gpio13: peripherals.pins.gpio13,
// gpio14: peripherals.pins.gpio14,
// gpio15: peripherals.pins.gpio15,
// gpio16: peripherals.pins.gpio16,
// gpio17: peripherals.pins.gpio17,
// gpio18: peripherals.pins.gpio18,
// gpio21: peripherals.pins.gpio21,
// gpio22: peripherals.pins.gpio22,
gpio23: peripherals.GPIO23,
// gpio24: peripherals.pins.gpio24,
// gpio25: peripherals.pins.gpio25,
// gpio26: peripherals.pins.gpio26,
// gpio27: peripherals.pins.gpio27,
// gpio28: peripherals.pins.gpio28,
// gpio29: peripherals.pins.gpio29,
// gpio30: peripherals.pins.gpio30,
};
//
let tablebuffer = mk_static!(
[u8; esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN],
[0u8; esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN]
);
let storage_ota = mk_static!(FlashStorage, FlashStorage::new());
let pt =
esp_bootloader_esp_idf::partitions::read_partition_table(storage_ota, tablebuffer)?;
// List all partitions - this is just FYI
for i in 0..pt.len() {
info!("{:?}", pt.get_partition(i));
}
let ota_data = mk_static!(
PartitionEntry,
pt.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::Data(
DataPartitionSubType::Ota,
))?
.expect("No OTA data partition found")
);
let ota_data = mk_static!(
FlashRegion<FlashStorage>,
ota_data.as_embedded_storage(storage_ota)
);
let mut ota = esp_bootloader_esp_idf::ota::Ota::new(ota_data)?;
let ota_partition = match ota.current_slot()? {
Slot::None => {
panic!("No OTA slot active?");
}
Slot::Slot0 => pt
.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::App(
AppPartitionSubType::Ota0,
))?
.expect("No OTA slot0 found"),
Slot::Slot1 => pt
.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::App(
AppPartitionSubType::Ota1,
))?
.expect("No OTA slot1 found"),
};
let ota_next = mk_static!(PartitionEntry, ota_partition);
let storage_ota = mk_static!(FlashStorage, FlashStorage::new());
let ota_next = mk_static!(
FlashRegion<FlashStorage>,
ota_next.as_embedded_storage(storage_ota)
);
let data_partition = pt
.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::Data(
DataPartitionSubType::LittleFs,
))?
.expect("Data partition with littlefs not found");
let data_partition = mk_static!(PartitionEntry, data_partition);
let storage_data = mk_static!(FlashStorage, FlashStorage::new());
let data = mk_static!(
FlashRegion<FlashStorage>,
data_partition.as_embedded_storage(storage_data)
);
let lfs2filesystem = mk_static!(LittleFs2Filesystem, LittleFs2Filesystem { storage: data });
let alloc = mk_static!(Allocation<LittleFs2Filesystem>, lfs2Filesystem::allocate());
if lfs2filesystem.is_mountable() {
log::info!("Littlefs2 filesystem is mountable");
} else {
match lfs2filesystem.format() {
Result::Ok(..) => {
log::info!("Littlefs2 filesystem is formatted");
}
Err(err) => {
bail!("Littlefs2 filesystem could not be formatted: {:?}", err);
}
}
}
let fs = Arc::new(Mutex::new(
lfs2Filesystem::mount(alloc, lfs2filesystem).expect("Could not mount lfs2 filesystem"),
));
let mut esp = Esp {
mqtt_client: None,
wifi_driver,
fs,
rng,
controller: Arc::new(Mutex::new(controller)),
interfaces: Some(interfaces),
boot_button,
delay: Delay::new(1000),
mqtt_client: None,
ota,
ota_next,
wall_clock_offset: 0,
};
//init,reset rtc memory depending on cause
let mut init_rtc_store: bool = false;
let mut to_config_mode: bool = false;
let reasons = ResetReason::get();
match reasons {
ResetReason::Software => {}
ResetReason::ExternalPin => {}
ResetReason::Watchdog => {
init_rtc_store = true;
let reasons = match reset_reason() {
None => {
"unknown"
}
ResetReason::Sdio => init_rtc_store = true,
ResetReason::Panic => init_rtc_store = true,
ResetReason::InterruptWatchdog => init_rtc_store = true,
ResetReason::PowerOn => init_rtc_store = true,
ResetReason::Unknown => init_rtc_store = true,
ResetReason::Brownout => init_rtc_store = true,
ResetReason::TaskWatchdog => init_rtc_store = true,
ResetReason::DeepSleep => {}
ResetReason::USBPeripheral => {
init_rtc_store = true;
to_config_mode = true;
Some(reason) => {
match reason {
SocResetReason::ChipPowerOn => {
"power on"
}
SocResetReason::CoreSw => {
"software reset"
}
SocResetReason::CoreDeepSleep => {
"deep sleep"
}
SocResetReason::CoreSDIO => {
"sdio reset"
}
SocResetReason::CoreMwdt0 => {
"Watchdog Main"
}
SocResetReason::CoreMwdt1 => {
"Watchdog 1"
}
SocResetReason::CoreRtcWdt => {
"Watchdog RTC"
}
SocResetReason::Cpu0Mwdt0 => {
"Watchdog MCpu0"
}
SocResetReason::Cpu0Sw => {
"software reset cpu0"
}
SocResetReason::Cpu0RtcWdt => {
init_rtc_store = true;
"Watchdog RTC cpu0"
}
SocResetReason::SysBrownOut => {
"sys brown out"
}
SocResetReason::SysRtcWdt => {
"Watchdog Sys rtc"
}
SocResetReason::Cpu0Mwdt1 => {
"cpu0 mwdt1"
}
SocResetReason::SysSuperWdt => {
"Watchdog Super"
}
SocResetReason::CoreEfuseCrc => {
"core efuse crc"
}
SocResetReason::CoreUsbUart => {
to_config_mode = true;
"core usb uart"
}
SocResetReason::CoreUsbJtag => {
"core usb jtag"
}
SocResetReason::Cpu0JtagCpu => {
"cpu0 jtag cpu"
}
}
}
ResetReason::JTAG => init_rtc_store = true,
};
log(
LOG_ACCESS.lock().await.log(
LogMessage::ResetReason,
init_rtc_store as u32,
to_config_mode as u32,
"",
&format!("{reasons:?}"),
);
).await;
esp.init_rtc_deepsleep_memory(init_rtc_store, to_config_mode);
let fs_mount_error = esp.mount_file_system().is_err();
esp.init_rtc_deepsleep_memory(init_rtc_store, to_config_mode)
.await;
let config = esp.load_config();
let config = esp.load_config().await;
println!("Init rtc driver");
let mut rtc = Ds323x::new_ds3231(MutexDevice::new(&I2C_DRIVER));
log::info!("Init rtc driver");
// let mut rtc = Ds323x::new_ds3231(MutexDevice::new(&I2C_DRIVER));
//
// log::info!("Init rtc eeprom driver");
// let eeprom = {
// Eeprom24x::new_24x32(
// MutexDevice::new(&I2C_DRIVER),
// SlaveAddr::Alternative(true, true, true),
// )
// };
// let rtc_time = rtc.datetime();
// match rtc_time {
// OkStd(tt) => {
// log::info!("Rtc Module reports time at UTC {}", tt);
// }
// Err(err) => {
// log::info!("Rtc Module could not be read {:?}", err);
// }
// }
println!("Init rtc eeprom driver");
let eeprom = {
Eeprom24x::new_24x32(
MutexDevice::new(&I2C_DRIVER),
SlaveAddr::Alternative(true, true, true),
)
};
let rtc_time = rtc.datetime();
match rtc_time {
OkStd(tt) => {
println!("Rtc Module reports time at UTC {}", tt);
}
Err(err) => {
println!("Rtc Module could not be read {:?}", err);
}
}
let storage = Storage::new(eeprom, Delay::new(1000));
let rtc_module: Box<dyn RTCModuleInteraction + Send> =
Box::new(DS3231Module { rtc, storage }) as Box<dyn RTCModuleInteraction + Send>;
// let storage = Storage::new(eeprom, Delay::new(1000));
//let rtc_module: Box<dyn RTCModuleInteraction + Send> =
// Box::new(DS3231Module { rtc, storage }) as Box<dyn RTCModuleInteraction + Send>;
let hal = match config {
Result::Ok(config) => {
let battery_interaction: Box<dyn BatteryInteraction + Send> =
match config.hardware.battery {
BatteryBoardVersion::Disabled => Box::new(NoBatteryMonitor {}),
BatteryBoardVersion::BQ34Z100G1 => {
let mut battery_driver = Bq34z100g1Driver {
i2c: MutexDevice::new(&I2C_DRIVER),
delay: Delay::new(0),
flash_block_data: [0; 32],
};
let status = print_battery_bq34z100(&mut battery_driver);
match status {
OkStd(_) => {}
Err(err) => {
log(
LogMessage::BatteryCommunicationError,
0u32,
0,
"",
&format!("{err:?})"),
);
}
}
Box::new(BQ34Z100G1 { battery_driver })
}
// BatteryBoardVersion::BQ34Z100G1 => {
// let mut battery_driver = Bq34z100g1Driver {
// i2c: MutexDevice::new(&I2C_DRIVER),
// delay: Delay::new(0),
// flash_block_data: [0; 32],
// };
// let status = print_battery_bq34z100(&mut battery_driver);
// match status {
// Ok(_) => {}
// Err(err) => {
// log(
// LogMessage::BatteryCommunicationError,
// 0u32,
// 0,
// "",
// &format!("{err:?})"),
// );
// }
// }
// Box::new(BQ34Z100G1 { battery_driver })
// }
BatteryBoardVersion::WchI2cSlave => {
// TODO use correct implementation once availible
Box::new(NoBatteryMonitor {})
}
_ => {
todo!()
}
};
let board_hal: Box<dyn BoardInteraction + Send> = match config.hardware.board {
BoardVersion::INITIAL => {
initial_hal::create_initial_board(free_pins, fs_mount_error, config, esp)?
}
BoardVersion::V3 => {
v3_hal::create_v3(free_pins, esp, config, battery_interaction, rtc_module)?
}
BoardVersion::V4 => {
v4_hal::create_v4(free_pins, esp, config, battery_interaction, rtc_module)?
}
};
let board_hal: Box<dyn BoardInteraction + Send> = //match config.hardware.board {
//BoardVersion::INITIAL => {
initial_hal::create_initial_board(free_pins, config, esp)?
;
//}
// BoardVersion::V3 => {
// v3_hal::create_v3(free_pins, esp, config, battery_interaction, rtc_module)?
// }
//BoardVersion::V4 => {
// v4_hal::create_v4(free_pins, esp, config, battery_interaction, rtc_module)?
//}
//_ => {
// todo!()
//}
//};
HAL { board_hal }
}
Err(err) => {
log(
LOG_ACCESS.lock().await.log(
LogMessage::ConfigModeMissingConfig,
0,
0,
"",
&err.to_string(),
);
).await;
HAL {
board_hal: initial_hal::create_initial_board(
free_pins,
fs_mount_error,
PlantControllerConfig::default(),
esp,
)?,
@@ -359,3 +526,12 @@ impl PlantHal {
Ok(Mutex::new(hal))
}
}
pub async fn esp_time() -> DateTime<Utc> {
DateTime::from_timestamp_micros(TIME_ACCESS.get().await.current_time_us() as i64).unwrap()
}
pub async fn esp_set_time(time: DateTime<FixedOffset>) {
TIME_ACCESS.get().await.set_current_time_us(time.timestamp_micros() as u64);
}

View File

@@ -1,132 +1,138 @@
use anyhow::{anyhow, bail};
use bincode::config::Configuration;
use bincode::{config, Decode, Encode};
use crate::hal::Box;
use alloc::vec::Vec;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use ds323x::{DateTimeAccess, Ds323x};
use eeprom24x::addr_size::TwoBytes;
use eeprom24x::page_size::B32;
use eeprom24x::unique_serial::No;
use eeprom24x::Storage;
use embedded_hal_bus::i2c::MutexDevice;
use embedded_storage::ReadStorage as embedded_storage_ReadStorage;
use embedded_storage::Storage as embedded_storage_Storage;
use esp_idf_hal::delay::Delay;
use esp_idf_hal::i2c::I2cDriver;
use serde::{Deserialize, Serialize};
use std::result::Result::Ok as OkStd;
const X25: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC);
const CONFIG: Configuration = config::standard();
// use crate::hal::Box;
// use alloc::vec::Vec;
// use anyhow::{anyhow, bail};
// use async_trait::async_trait;
// use bincode::config::Configuration;
// use bincode::{config, Decode, Encode};
// use chrono::{DateTime, Utc};
// use ds323x::{DateTimeAccess, Ds323x};
// use eeprom24x::addr_size::TwoBytes;
// use eeprom24x::page_size::B32;
// use eeprom24x::unique_serial::No;
// use eeprom24x::Storage;
// use embedded_storage::ReadStorage as embedded_storage_ReadStorage;
// use embedded_storage::Storage as embedded_storage_Storage;
// use serde::{Deserialize, Serialize};
//
// const X25: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC);
// const CONFIG: Configuration = config::standard();
//
#[async_trait]
pub trait RTCModuleInteraction {
fn get_backup_info(&mut self) -> anyhow::Result<BackupHeader>;
fn get_backup_config(&mut self) -> anyhow::Result<Vec<u8>>;
fn backup_config(&mut self, bytes: &[u8]) -> anyhow::Result<()>;
fn get_rtc_time(&mut self) -> anyhow::Result<DateTime<Utc>>;
fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> anyhow::Result<()>;
async fn get_backup_info(&mut self) -> anyhow::Result<BackupHeader>;
async fn get_backup_config(&mut self) -> anyhow::Result<Vec<u8>>;
async fn backup_config(&mut self, bytes: &[u8]) -> anyhow::Result<()>;
async fn get_rtc_time(&mut self) -> anyhow::Result<DateTime<Utc>>;
async fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> anyhow::Result<()>;
}
const BACKUP_HEADER_MAX_SIZE: usize = 64;
#[derive(Serialize, Deserialize, PartialEq, Debug, Default, Encode, Decode)]
//
// const BACKUP_HEADER_MAX_SIZE: usize = 64;
// #[derive(Serialize, Deserialize, PartialEq, Debug, Default, Encode, Decode)]
pub struct BackupHeader {
pub timestamp: i64,
crc16: u16,
pub size: u16,
}
pub struct DS3231Module<'a> {
pub(crate) rtc:
Ds323x<ds323x::interface::I2cInterface<MutexDevice<'a, I2cDriver<'a>>>, ds323x::ic::DS3231>,
pub(crate) storage: Storage<MutexDevice<'a, I2cDriver<'a>>, B32, TwoBytes, No, Delay>,
}
impl RTCModuleInteraction for DS3231Module<'_> {
fn get_backup_info(&mut self) -> anyhow::Result<BackupHeader> {
let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
self.storage
.read(0, &mut header_page_buffer)
.map_err(|err| anyhow!("Error reading eeprom header {:?}", err))?;
let (header, len): (BackupHeader, usize) =
bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
println!("Raw header is {:?} with size {}", header_page_buffer, len);
anyhow::Ok(header)
}
fn get_backup_config(&mut self) -> anyhow::Result<Vec<u8>> {
let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
self.storage
.read(0, &mut header_page_buffer)
.map_err(|err| anyhow!("Error reading eeprom header {:?}", err))?;
let (header, _header_size): (BackupHeader, usize) =
bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
let mut data_buffer = vec![0_u8; header.size as usize];
//read the specified number of bytes after the header
self.storage
.read(BACKUP_HEADER_MAX_SIZE as u32, &mut data_buffer)
.map_err(|err| anyhow!("Error reading eeprom data {:?}", err))?;
let checksum = X25.checksum(&data_buffer);
if checksum != header.crc16 {
bail!(
"Invalid checksum, got {} but expected {}",
checksum,
header.crc16
);
}
anyhow::Ok(data_buffer)
}
fn backup_config(&mut self, bytes: &[u8]) -> anyhow::Result<()> {
let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
let time = self.get_rtc_time()?.timestamp_millis();
let checksum = X25.checksum(bytes);
let header = BackupHeader {
crc16: checksum,
timestamp: time,
size: bytes.len() as u16,
};
let config = config::standard();
let encoded = bincode::encode_into_slice(&header, &mut header_page_buffer, config)?;
println!(
"Raw header is {:?} with size {}",
header_page_buffer, encoded
);
self.storage
.write(0, &header_page_buffer)
.map_err(|err| anyhow!("Error writing header {:?}", err))?;
//write rest after the header
self.storage
.write(BACKUP_HEADER_MAX_SIZE as u32, &bytes)
.map_err(|err| anyhow!("Error writing body {:?}", err))?;
anyhow::Ok(())
}
fn get_rtc_time(&mut self) -> anyhow::Result<DateTime<Utc>> {
match self.rtc.datetime() {
OkStd(rtc_time) => anyhow::Ok(rtc_time.and_utc()),
Err(err) => {
bail!("Error getting rtc time {:?}", err)
}
}
}
fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> anyhow::Result<()> {
let naive_time = time.naive_utc();
match self.rtc.set_datetime(&naive_time) {
OkStd(_) => anyhow::Ok(()),
Err(err) => {
bail!("Error getting rtc time {:?}", err)
}
}
}
}
//
// pub struct DS3231Module<'a> {
// pub(crate) rtc:
// Ds323x<ds323x::interface::I2cInterface<MutexDevice<'a, I2cDriver<'a>>>, ds323x::ic::DS3231>,
//
// pub(crate) storage: Storage<MutexDevice<'a, I2cDriver<'a>>, B32, TwoBytes, No, Delay>,
// }
//
// impl RTCModuleInteraction for DS3231Module<'_> {
// fn get_backup_info(&mut self) -> anyhow::Result<BackupHeader> {
// let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
//
// self.storage
// .read(0, &mut header_page_buffer)
// .map_err(|err| anyhow!("Error reading eeprom header {:?}", err))?;
//
// let (header, len): (BackupHeader, usize) =
// bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
//
// log::info!("Raw header is {:?} with size {}", header_page_buffer, len);
// anyhow::Ok(header)
// }
//
// fn get_backup_config(&mut self) -> anyhow::Result<Vec<u8>> {
// let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
//
// self.storage
// .read(0, &mut header_page_buffer)
// .map_err(|err| anyhow!("Error reading eeprom header {:?}", err))?;
// let (header, _header_size): (BackupHeader, usize) =
// bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
//
// let mut data_buffer = vec![0_u8; header.size as usize];
// //read the specified number of bytes after the header
// self.storage
// .read(BACKUP_HEADER_MAX_SIZE as u32, &mut data_buffer)
// .map_err(|err| anyhow!("Error reading eeprom data {:?}", err))?;
//
// let checksum = X25.checksum(&data_buffer);
// if checksum != header.crc16 {
// bail!(
// "Invalid checksum, got {} but expected {}",
// checksum,
// header.crc16
// );
// }
//
// anyhow::Ok(data_buffer)
// }
// fn backup_config(&mut self, bytes: &[u8]) -> anyhow::Result<()> {
// let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
//
// let time = self.get_rtc_time()?.timestamp_millis();
// let checksum = X25.checksum(bytes);
//
// let header = BackupHeader {
// crc16: checksum,
// timestamp: time,
// size: bytes.len() as u16,
// };
// let config = config::standard();
// let encoded = bincode::encode_into_slice(&header, &mut header_page_buffer, config)?;
// log::info!(
// "Raw header is {:?} with size {}",
// header_page_buffer,
// encoded
// );
// self.storage
// .write(0, &header_page_buffer)
// .map_err(|err| anyhow!("Error writing header {:?}", err))?;
//
// //write rest after the header
// self.storage
// .write(BACKUP_HEADER_MAX_SIZE as u32, &bytes)
// .map_err(|err| anyhow!("Error writing body {:?}", err))?;
//
// anyhow::Ok(())
// }
//
// fn get_rtc_time(&mut self) -> anyhow::Result<DateTime<Utc>> {
// match self.rtc.datetime() {
// OkStd(rtc_time) => anyhow::Ok(rtc_time.and_utc()),
// Err(err) => {
// bail!("Error getting rtc time {:?}", err)
// }
// }
// }
//
// fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> anyhow::Result<()> {
// let naive_time = time.naive_utc();
// match self.rtc.set_datetime(&naive_time) {
// OkStd(_) => anyhow::Ok(()),
// Err(err) => {
// bail!("Error getting rtc time {:?}", err)
// }
// }
// }
// }

View File

@@ -1,170 +0,0 @@
use crate::hal::TANK_MULTI_SAMPLE;
use anyhow::{anyhow, bail};
use ds18b20::Ds18b20;
use esp_idf_hal::adc::oneshot::config::AdcChannelConfig;
use esp_idf_hal::adc::oneshot::{AdcChannelDriver, AdcDriver};
use esp_idf_hal::adc::{attenuation, Resolution, ADC1};
use esp_idf_hal::delay::Delay;
use esp_idf_hal::gpio::{AnyIOPin, AnyInputPin, Gpio5, InputOutput, PinDriver, Pull};
use esp_idf_hal::pcnt::{PcntChannel, PcntChannelConfig, PcntControlMode, PcntCountMode, PcntDriver, PinIndex, PCNT1};
use esp_idf_sys::EspError;
use one_wire_bus::OneWire;
pub struct TankSensor<'a> {
one_wire_bus: OneWire<PinDriver<'a, AnyIOPin, InputOutput>>,
tank_channel: AdcChannelDriver<'a, Gpio5, AdcDriver<'a, ADC1>>,
tank_power: PinDriver<'a, AnyIOPin, InputOutput>,
flow_counter: PcntDriver<'a>,
delay: Delay,
}
impl<'a> TankSensor<'a> {
pub(crate) fn create(
one_wire_pin: AnyIOPin,
adc1: ADC1,
gpio5: Gpio5,
tank_power_pin: AnyIOPin,
flow_sensor_pin: AnyIOPin,
pcnt1: PCNT1
) -> anyhow::Result<TankSensor<'a>> {
let mut one_wire_pin =
PinDriver::input_output_od(one_wire_pin).expect("Failed to configure pin");
one_wire_pin
.set_pull(Pull::Floating)
.expect("Failed to set pull");
let adc_config = AdcChannelConfig {
attenuation: attenuation::DB_11,
resolution: Resolution::Resolution12Bit,
calibration: esp_idf_hal::adc::oneshot::config::Calibration::Curve,
};
let tank_driver = AdcDriver::new(adc1).expect("Failed to configure ADC");
let tank_channel = AdcChannelDriver::new(tank_driver, gpio5, &adc_config)
.expect("Failed to configure ADC channel");
let mut tank_power =
PinDriver::input_output(tank_power_pin).expect("Failed to configure pin");
tank_power
.set_pull(Pull::Floating)
.expect("Failed to set pull");
let one_wire_bus =
OneWire::new(one_wire_pin).expect("OneWire bus did not pull up after release");
let mut flow_counter = PcntDriver::new(
pcnt1,
Some(flow_sensor_pin),
Option::<AnyInputPin>::None,
Option::<AnyInputPin>::None,
Option::<AnyInputPin>::None,
)?;
flow_counter.channel_config(
PcntChannel::Channel1,
PinIndex::Pin0,
PinIndex::Pin1,
&PcntChannelConfig {
lctrl_mode: PcntControlMode::Keep,
hctrl_mode: PcntControlMode::Keep,
pos_mode: PcntCountMode::Increment,
neg_mode: PcntCountMode::Hold,
counter_h_lim: i16::MAX,
counter_l_lim: 0,
},
)?;
Ok(TankSensor {
one_wire_bus,
tank_channel,
tank_power,
flow_counter,
delay: Default::default(),
})
}
pub fn reset_flow_meter(&mut self) {
self.flow_counter.counter_pause().unwrap();
self.flow_counter.counter_clear().unwrap();
}
pub fn start_flow_meter(&mut self) {
self.flow_counter.counter_resume().unwrap();
}
pub fn get_flow_meter_value(&mut self) -> i16 {
self.flow_counter.get_counter_value().unwrap()
}
pub fn stop_flow_meter(&mut self) -> i16 {
self.flow_counter.counter_pause().unwrap();
self.get_flow_meter_value()
}
pub fn water_temperature_c(&mut self) -> anyhow::Result<f32> {
//multisample should be moved to water_temperature_c
let mut attempt = 1;
let water_temp: Result<f32, anyhow::Error> = loop {
let temp = self.single_temperature_c();
match &temp {
Ok(res) => {
println!("Water temp is {}", res);
break temp;
}
Err(err) => {
println!("Could not get water temp {} attempt {}", err, attempt)
}
}
if attempt == 5 {
break temp;
}
attempt += 1;
};
water_temp
}
fn single_temperature_c(&mut self) -> anyhow::Result<f32> {
self.one_wire_bus
.reset(&mut self.delay)
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
let first = self.one_wire_bus.devices(false, &mut self.delay).next();
if first.is_none() {
bail!("Not found any one wire Ds18b20");
}
let device_address = first
.unwrap()
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
let water_temp_sensor = Ds18b20::new::<EspError>(device_address)
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
water_temp_sensor
.start_temp_measurement(&mut self.one_wire_bus, &mut self.delay)
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
ds18b20::Resolution::Bits12.delay_for_measurement_time(&mut self.delay);
let sensor_data = water_temp_sensor
.read_data(&mut self.one_wire_bus, &mut self.delay)
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
if sensor_data.temperature == 85_f32 {
bail!("Ds18b20 dummy temperature returned");
}
anyhow::Ok(sensor_data.temperature / 10_f32)
}
pub fn tank_sensor_voltage(&mut self) -> anyhow::Result<f32> {
self.tank_power.set_high()?;
//let stabilize
self.delay.delay_ms(100);
let mut store = [0_u16; TANK_MULTI_SAMPLE];
for multisample in 0..TANK_MULTI_SAMPLE {
let value = self.tank_channel.read()?;
store[multisample] = value;
}
self.tank_power.set_low()?;
store.sort();
let median_mv = store[6] as f32 / 1000_f32;
anyhow::Ok(median_mv)
}
}

View File

@@ -1,4 +0,0 @@
#![allow(dead_code)]
extern crate embedded_hal as hal;
pub mod sipo;

View File

@@ -1,42 +1,122 @@
use crate::vec;
use alloc::string::ToString;
use alloc::vec::Vec;
use bytemuck::{AnyBitPattern, Contiguous, Pod, Zeroable};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::mutex::Mutex;
use embassy_time::Instant;
use esp_hal::Persistable;
use log::info;
use serde::Serialize;
use std::{collections::HashMap, sync::Mutex};
use strum::EnumIter;
use strum_macros::IntoStaticStr;
use esp_idf_svc::systime::EspSystemTime;
use once_cell::sync::Lazy;
use ringbuffer::{ConstGenericRingBuffer, RingBuffer};
use text_template::Template;
use unit_enum::UnitEnum;
use crate::hal::TIME_ACCESS;
#[esp_hal::ram(rtc_fast, persistent)]
static mut LOG_ARRAY: LogArray = LogArray {
buffer: [LogEntryInner { timestamp: 0, message_id: 0, a: 0, b: 0, txt_short: [0;TXT_SHORT_LENGTH], txt_long: [0;TXT_LONG_LENGTH] }; 256],
head: 0,
};
pub static LOG_ACCESS: Mutex<CriticalSectionRawMutex, LogArray> = Mutex::new(unsafe { LOG_ARRAY });
const TXT_SHORT_LENGTH: usize = 8;
const TXT_LONG_LENGTH: usize = 32;
const BUFFER_SIZE: usize = 220;
#[link_section = ".rtc.data"]
static mut BUFFER: ConstGenericRingBuffer<LogEntry, BUFFER_SIZE> =
ConstGenericRingBuffer::<LogEntry, BUFFER_SIZE>::new();
#[allow(static_mut_refs)]
static BUFFER_ACCESS: Lazy<Mutex<&mut ConstGenericRingBuffer<LogEntry, BUFFER_SIZE>>> =
Lazy::new(|| unsafe { Mutex::new(&mut BUFFER) });
#[derive(Debug, Clone, Copy, AnyBitPattern)]
#[repr(C)]
pub struct LogArray{
buffer: [LogEntryInner; (u8::MAX_VALUE as usize) +1],
head: u8
}
#[derive(Serialize, Debug, Clone)]
unsafe impl Persistable for LogArray {}
unsafe impl Zeroable for LogEntryInner {}
unsafe impl Pod for LogEntryInner{}
#[derive(Debug, Clone, Copy)]
struct LogEntryInner {
pub timestamp: u64,
pub message_id: u16,
pub a: u32,
pub b: u32,
pub txt_short: [u8; TXT_SHORT_LENGTH],
pub txt_long: [u8; TXT_LONG_LENGTH],
}
#[derive(Serialize)]
pub struct LogEntry {
pub timestamp: u64,
pub message_id: u16,
pub a: u32,
pub b: u32,
pub txt_short: heapless::String<TXT_SHORT_LENGTH>,
pub txt_long: heapless::String<TXT_LONG_LENGTH>,
pub txt_short: alloc::string::String,
pub txt_long: alloc::string::String,
}
pub fn init() {
unsafe {
BUFFER = ConstGenericRingBuffer::<LogEntry, BUFFER_SIZE>::new();
};
let mut access = BUFFER_ACCESS.lock().unwrap();
access.drain().for_each(|_| {});
impl From<LogEntryInner> for LogEntry {
fn from(value: LogEntryInner) -> Self {
LogEntry{
timestamp: value.timestamp,
message_id: value.message_id,
a: value.a,
b: value.b,
txt_short: alloc::string::String::from_utf8_lossy_owned(value.txt_short.to_vec()),
txt_long: alloc::string::String::from_utf8_lossy_owned(value.txt_long.to_vec()),
}
}
}
impl LogArray {
pub fn get(&mut self) -> Vec<LogEntry> {
let mut rv: Vec<LogEntry> = Vec::new();
let mut index = self.head.wrapping_sub(1);
for _ in 0..self.buffer.len() {
let entry = self.buffer[index as usize];
if (entry.message_id as usize) != LogMessage::Empty.ordinal() {
rv.push(entry.into());
}
index = index.wrapping_sub(1);
}
rv
}
pub async fn log(
&mut self,
message_key: LogMessage,
number_a: u32,
number_b: u32,
txt_short: &str,
txt_long: &str,
) {
let mut txt_short_stack: heapless::String<TXT_SHORT_LENGTH> = heapless::String::new();
let mut txt_long_stack: heapless::String<TXT_LONG_LENGTH> = heapless::String::new();
limit_length(txt_short, &mut txt_short_stack);
limit_length(txt_long, &mut txt_long_stack);
let time = TIME_ACCESS.get().await.current_time_us()/1000;
let ordinal = message_key.ordinal() as u16;
let template: &str = message_key.into();
let mut template_string = template.to_string();
template_string = template_string.replace("${number_a}", number_a.to_string().as_str());
template_string = template_string.replace("${number_b}", number_b.to_string().as_str());
template_string = template_string.replace("${txt_long}", txt_long);
template_string = template_string.replace("${txt_short}", txt_short);
info!("{}", template_string);
let to_modify = &mut self.buffer[self.head as usize];
to_modify.timestamp = time;
to_modify.message_id = ordinal;
to_modify.a = number_a;
to_modify.b = number_b;
to_modify.txt_short.clone_from_slice(&txt_short_stack.as_bytes());
to_modify.txt_long.clone_from_slice(&txt_long_stack.as_bytes());
self.head = self.head.wrapping_add(1);
}
}
fn limit_length<const LIMIT: usize>(input: &str, target: &mut heapless::String<LIMIT>) {
@@ -55,79 +135,19 @@ fn limit_length<const LIMIT: usize>(input: &str, target: &mut heapless::String<L
}
}
}
}
pub fn get_log() -> Vec<LogEntry> {
let buffer = BUFFER_ACCESS.lock().unwrap();
let mut read_copy = Vec::new();
for entry in buffer.iter() {
let copy = entry.clone();
read_copy.push(copy);
}
drop(buffer);
read_copy
}
pub fn log(message_key: LogMessage, number_a: u32, number_b: u32, txt_short: &str, txt_long: &str) {
let mut txt_short_stack: heapless::String<TXT_SHORT_LENGTH> = heapless::String::new();
let mut txt_long_stack: heapless::String<TXT_LONG_LENGTH> = heapless::String::new();
limit_length(txt_short, &mut txt_short_stack);
limit_length(txt_long, &mut txt_long_stack);
let time = EspSystemTime {}.now().as_millis() as u64;
let ordinal = message_key.ordinal() as u16;
let template_string: &str = message_key.into();
let mut values: HashMap<&str, &str> = HashMap::new();
let number_a_str = number_a.to_string();
let number_b_str = number_b.to_string();
values.insert("number_a", &number_a_str);
values.insert("number_b", &number_b_str);
values.insert("txt_short", txt_short);
values.insert("txt_long", txt_long);
let template = Template::from(template_string);
let serial_entry = template.fill_in(&values);
println!("{serial_entry}");
//TODO push to mqtt?
let entry = LogEntry {
timestamp: time,
message_id: ordinal,
a: number_a,
b: number_b,
txt_short: txt_short_stack,
txt_long: txt_long_stack,
};
let mut buffer = BUFFER_ACCESS.lock().unwrap();
buffer.push(entry);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn within_limit() {
let test = "12345678";
let mut txt_short_stack: heapless::String<TXT_SHORT_LENGTH> = heapless::String::new();
let mut txt_long_stack: heapless::String<TXT_LONG_LENGTH> = heapless::String::new();
limit_length(test, &mut txt_short_stack);
limit_length(test, &mut txt_long_stack);
assert_eq!(txt_short_stack.as_str(), test);
assert_eq!(txt_long_stack.as_str(), test);
while target.len() < LIMIT {
target.push(' ').unwrap();
}
}
#[derive(IntoStaticStr, EnumIter, Serialize, PartialEq, Eq, PartialOrd, Ord, Clone, UnitEnum)]
#[derive(IntoStaticStr, Serialize, PartialEq, Eq, PartialOrd, Ord, Clone, UnitEnum)]
pub enum LogMessage {
#[strum(
serialize = ""
)]
Empty,
#[strum(
serialize = "Reset due to ${txt_long} requires rtc clear ${number_a} and force config mode ${number_b}"
)]

File diff suppressed because it is too large Load Diff

View File

@@ -3,6 +3,7 @@ use crate::{
hal::{Sensor, HAL},
in_time_range,
};
use alloc::string::{String, ToString};
use chrono::{DateTime, TimeDelta, Utc};
use chrono_tz::Tz;
use serde::{Deserialize, Serialize};
@@ -78,6 +79,7 @@ impl PumpState {
pub enum PlantWateringMode {
OFF,
TargetMoisture,
MinMoisture,
TimerOnly,
}
@@ -114,9 +116,9 @@ fn map_range_moisture(
}
impl PlantState {
pub fn read_hardware_state(plant_id: usize, board: &mut HAL) -> Self {
pub async fn read_hardware_state(plant_id: usize, board: &mut HAL<'_>) -> Self {
let sensor_a = if board.board_hal.get_config().plants[plant_id].sensor_a {
match board.board_hal.measure_moisture_hz(plant_id, Sensor::A) {
match board.board_hal.measure_moisture_hz(plant_id, Sensor::A).await {
Ok(raw) => match map_range_moisture(
raw,
board.board_hal.get_config().plants[plant_id].moisture_sensor_min_frequency,
@@ -137,7 +139,7 @@ impl PlantState {
};
let sensor_b = if board.board_hal.get_config().plants[plant_id].sensor_b {
match board.board_hal.measure_moisture_hz(plant_id, Sensor::B) {
match board.board_hal.measure_moisture_hz(plant_id, Sensor::B).await {
Ok(raw) => match map_range_moisture(
raw,
board.board_hal.get_config().plants[plant_id].moisture_sensor_min_frequency,
@@ -235,51 +237,77 @@ impl PlantState {
false
}
}
PlantWateringMode::MinMoisture => {
let (moisture_percent, _) = self.plant_moisture();
if let Some(_moisture_percent) = moisture_percent {
if self.pump_in_timeout(plant_conf, current_time) {
false
} else if !in_time_range(
current_time,
plant_conf.pump_hour_start,
plant_conf.pump_hour_end,
) {
false
} else if true {
//if not cooldown min and below max
true
} else if true {
//if below min disable cooldown min
true
} else {
false
}
} else {
false
}
}
PlantWateringMode::TimerOnly => !self.pump_in_timeout(plant_conf, current_time),
}
}
pub fn to_mqtt_info(
&self,
plant_conf: &PlantConfig,
current_time: &DateTime<Tz>,
) -> PlantInfo<'_> {
PlantInfo {
sensor_a: &self.sensor_a,
sensor_b: &self.sensor_b,
mode: plant_conf.mode,
do_water: self.needs_to_be_watered(plant_conf, current_time),
dry: if let Some(moisture_percent) = self.plant_moisture().0 {
moisture_percent < plant_conf.target_moisture
} else {
false
},
cooldown: self.pump_in_timeout(plant_conf, current_time),
out_of_work_hour: in_time_range(
current_time,
plant_conf.pump_hour_start,
plant_conf.pump_hour_end,
),
consecutive_pump_count: self.pump.consecutive_pump_count,
pump_error: self.pump.is_err(plant_conf),
last_pump: self
.pump
.previous_pump
.map(|t| t.with_timezone(&current_time.timezone())),
next_pump: if matches!(
plant_conf.mode,
PlantWateringMode::TimerOnly | PlantWateringMode::TargetMoisture
) {
self.pump.previous_pump.and_then(|last_pump| {
last_pump
.checked_add_signed(TimeDelta::minutes(plant_conf.pump_cooldown_min.into()))
.map(|t| t.with_timezone(&current_time.timezone()))
})
} else {
None
},
}
}
//
// pub fn to_mqtt_info(
// &self,
// plant_conf: &PlantConfig,
// current_time: &DateTime<Tz>,
// ) -> PlantInfo<'_> {
// PlantInfo {
// sensor_a: &self.sensor_a,
// sensor_b: &self.sensor_b,
// mode: plant_conf.mode,
// do_water: self.needs_to_be_watered(plant_conf, current_time),
// dry: if let Some(moisture_percent) = self.plant_moisture().0 {
// moisture_percent < plant_conf.target_moisture
// } else {
// false
// },
// cooldown: self.pump_in_timeout(plant_conf, current_time),
// out_of_work_hour: in_time_range(
// current_time,
// plant_conf.pump_hour_start,
// plant_conf.pump_hour_end,
// ),
// consecutive_pump_count: self.pump.consecutive_pump_count,
// pump_error: self.pump.is_err(plant_conf),
// last_pump: self
// .pump
// .previous_pump
// .map(|t| t.with_timezone(&current_time.timezone())),
// next_pump: if matches!(
// plant_conf.mode,
// PlantWateringMode::TimerOnly
// | PlantWateringMode::TargetMoisture
// | PlantWateringMode::MinMoisture
// ) {
// self.pump.previous_pump.and_then(|last_pump| {
// last_pump
// .checked_add_signed(TimeDelta::minutes(plant_conf.pump_cooldown_min.into()))
// .map(|t| t.with_timezone(&current_time.timezone()))
// })
// } else {
// None
// },
// }
// }
}
#[derive(Debug, PartialEq, Serialize)]
@@ -302,8 +330,8 @@ pub struct PlantInfo<'a> {
/// how often has the pump been watered without reaching target moisture
consecutive_pump_count: u32,
pump_error: Option<PumpError>,
/// last time when the pump was active
last_pump: Option<DateTime<Tz>>,
/// next time when pump should activate
next_pump: Option<DateTime<Tz>>,
// /// last time when the pump was active
// last_pump: Option<DateTime<Tz>>,
// /// next time when pump should activate
// next_pump: Option<DateTime<Tz>>,
}

View File

@@ -1,10 +1,11 @@
//! Serial-in parallel-out shift register
use core::cell::RefCell;
use core::convert::Infallible;
use core::iter::Iterator;
use core::mem::{self, MaybeUninit};
use std::convert::Infallible;
use hal::digital::OutputPin;
use core::result::{Result, Result::Ok};
use embedded_hal::digital::OutputPin;
trait ShiftRegisterInternal {
fn update(&self, index: usize, command: bool) -> Result<(), ()>;

View File

@@ -1,5 +1,5 @@
use crate::{config::TankConfig, hal::HAL};
use anyhow::Context;
use crate::alloc::string::{String, ToString};
use crate::config::TankConfig;
use serde::Serialize;
const OPEN_TANK_VOLTAGE: f32 = 3.0;
@@ -150,21 +150,21 @@ impl TankState {
}
}
pub fn determine_tank_state(board: &mut std::sync::MutexGuard<'_, HAL<'_>>) -> TankState {
if board.board_hal.get_config().tank.tank_sensor_enabled {
match board
.board_hal
.get_tank_sensor()
.context("no sensor")
.and_then(|f| f.tank_sensor_voltage())
{
Ok(raw_sensor_value_mv) => TankState::Present(raw_sensor_value_mv),
Err(err) => TankState::Error(TankError::BoardError(err.to_string())),
}
} else {
TankState::Disabled
}
}
// pub fn determine_tank_state(board: &mut std::sync::MutexGuard<'_, HAL<'_>>) -> TankState {
// if board.board_hal.get_config().tank.tank_sensor_enabled {
// match board
// .board_hal
// .get_tank_sensor()
// .context("no sensor")
// .and_then(|f| f.tank_sensor_voltage())
// {
// Ok(raw_sensor_value_mv) => TankState::Present(raw_sensor_value_mv),
// Err(err) => TankState::Error(TankError::BoardError(err.to_string())),
// }
// } else {
// TankState::Disabled
// }
// }
#[derive(Debug, Serialize)]
/// Information structure send to mqtt for monitoring purposes

File diff suppressed because it is too large Load Diff

View File

@@ -29,6 +29,8 @@ export interface NetworkConfig {
password: string,
mqtt_url: string,
base_topic: string,
mqtt_user: string | null,
mqtt_password: string | null,
max_wait: number
}
@@ -105,6 +107,7 @@ export interface PlantControllerConfig {
export interface PlantConfig {
mode: string,
target_moisture: number,
min_moisture: number,
pump_time_s: number,
pump_cooldown_min: number,
pump_hour_start: number,

View File

@@ -72,8 +72,20 @@
</div>
<input class="mqttvalue" type="text" id="base_topic" placeholder="plants/one">
</div>
<div class="flexcontainer">
<div class="mqttkey">
MQTT User
</div>
<input class="mqttvalue" type="text" id="mqtt_user" placeholder="">
</div>
<div class="flexcontainer">
<div class="mqttkey">
MQTT Password
</div>
<input class="mqttvalue" type="text" id="mqtt_password" placeholder="">
</div>
</div>
</div>
</div>
</div>

View File

@@ -16,6 +16,8 @@ export class NetworkConfigView {
private readonly mqtt_url: HTMLInputElement;
private readonly base_topic: HTMLInputElement;
private readonly max_wait: HTMLInputElement;
private readonly mqtt_user: HTMLInputElement;
private readonly mqtt_password: HTMLInputElement;
private readonly ssidlist: HTMLElement;
constructor(controller: Controller, publicIp: string) {
@@ -37,6 +39,10 @@ export class NetworkConfigView {
this.mqtt_url.onchange = controller.configChanged
this.base_topic = document.getElementById("base_topic") as HTMLInputElement;
this.base_topic.onchange = controller.configChanged
this.mqtt_user = document.getElementById("mqtt_user") as HTMLInputElement;
this.mqtt_user.onchange = controller.configChanged
this.mqtt_password = document.getElementById("mqtt_password") as HTMLInputElement;
this.mqtt_password.onchange = controller.configChanged
this.ssidlist = document.getElementById("ssidlist") as HTMLElement
@@ -52,6 +58,8 @@ export class NetworkConfigView {
this.password.value = network.password;
this.mqtt_url.value = network.mqtt_url;
this.base_topic.value = network.base_topic;
this.mqtt_user.value = network.mqtt_user ?? "";
this.mqtt_password.value = network.mqtt_password ?? "";
this.max_wait.value = network.max_wait.toString();
}
@@ -62,7 +70,9 @@ export class NetworkConfigView {
ssid: this.ssid.value ?? null,
password: this.password.value ?? null,
mqtt_url: this.mqtt_url.value ?? null,
mqtt_user: this.mqtt_user.value ? this.mqtt_user.value : null,
mqtt_password: this.mqtt_password.value ? this.mqtt_password.value : null,
base_topic: this.base_topic.value ?? null
}
}
}
}

View File

@@ -55,6 +55,7 @@
<select class="plantvalue" id="plant_${plantId}_mode">
<option value="OFF">Off</option>
<option value="TargetMoisture">Target</option>
<option value="MinMoisture">Min Moisture</option>
<option value="TimerOnly">Timer</option>
</select>
@@ -63,6 +64,10 @@
<div class="plantkey">Target Moisture:</div>
<input class="plantvalue" id="plant_${plantId}_target_moisture" type="number" min="0" max="100" placeholder="0">
</div>
<div class="flexcontainer plantMinEnabledOnly_${plantId}">
<div class="plantkey">Minimum Moisture:</div>
<input class="plantvalue" id="plant_${plantId}_min_moisture" type="number" min="0" max="100" placeholder="0">
</div>
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
<div class="plantkey">Pump Time (s):</div>
<input class="plantvalue" id="plant_${plantId}_pump_time_s" type="number" min="0" max="600" placeholder="30">

View File

@@ -59,6 +59,7 @@ export class PlantView {
private readonly header: HTMLElement;
private readonly testButton: HTMLButtonElement;
private readonly targetMoisture: HTMLInputElement;
private readonly minMoisture: HTMLInputElement;
private readonly pumpTimeS: HTMLInputElement;
private readonly pumpCooldown: HTMLInputElement;
private readonly pumpHourStart: HTMLSelectElement;
@@ -118,6 +119,11 @@ export class PlantView {
controller.configChanged()
}
this.minMoisture = document.getElementById("plant_" + plantId + "_min_moisture")! as HTMLInputElement;
this.minMoisture.onchange = function () {
controller.configChanged()
}
this.pumpTimeS = document.getElementById("plant_" + plantId + "_pump_time_s") as HTMLInputElement;
this.pumpTimeS.onchange = function () {
controller.configChanged()
@@ -203,13 +209,15 @@ export class PlantView {
let sensorOnly = document.getElementsByClassName("plantSensorEnabledOnly_"+ this.plantId)
let pumpOnly = document.getElementsByClassName("plantPumpEnabledOnly_"+ this.plantId)
let targetOnly = document.getElementsByClassName("plantTargetEnabledOnly_"+ this.plantId)
let minOnly = document.getElementsByClassName("plantMinEnabledOnly_"+ this.plantId)
console.log("updateVisibility plantConfig: " + plantConfig.mode)
let showSensor = plantConfig.sensor_a || plantConfig.sensor_b
let showPump = plantConfig.mode !== "OFF"
let showTarget = plantConfig.mode === "TargetMoisture"
let showMin = plantConfig.mode === "MinMoisture"
console.log("updateVisibility showsensor: " + showSensor + " pump " + showPump + " target " +showTarget)
console.log("updateVisibility showsensor: " + showSensor + " pump " + showPump + " target " +showTarget + " min " + showMin)
for (const element of Array.from(sensorOnly)) {
if (showSensor) {
@@ -234,6 +242,14 @@ export class PlantView {
element.classList.add("plantHidden_" + this.plantId)
}
}
for (const element of Array.from(minOnly)) {
if (showMin) {
element.classList.remove("plantHidden_" + this.plantId)
} else {
element.classList.add("plantHidden_" + this.plantId)
}
}
}
setTestResult(result: PumpTestResult) {
@@ -255,6 +271,7 @@ export class PlantView {
setConfig(plantConfig: PlantConfig) {
this.mode.value = plantConfig.mode;
this.targetMoisture.value = plantConfig.target_moisture.toString();
this.minMoisture.value = plantConfig.min_moisture?.toString() || "";
this.pumpTimeS.value = plantConfig.pump_time_s.toString();
this.pumpCooldown.value = plantConfig.pump_cooldown_min.toString();
this.pumpHourStart.value = plantConfig.pump_hour_start.toString();
@@ -280,6 +297,7 @@ export class PlantView {
let conv: PlantConfig = {
mode: this.mode.value,
target_moisture: this.targetMoisture.valueAsNumber,
min_moisture: this.minMoisture.valueAsNumber,
pump_time_s: this.pumpTimeS.valueAsNumber,
pump_cooldown_min: this.pumpCooldown.valueAsNumber,
pump_hour_start: +this.pumpHourStart.value,