-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxymow.py
4621 lines (4144 loc) · 213 KB
/
proxymow.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from argparse import ArgumentParser
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path
import glob
import json
import cherrypy
from jinja2 import Environment, FileSystemLoader
import random
import io
import os
import tempfile
import platform
import gc
import datetime
from datetime import timezone
import time
from time import sleep
from math import radians, degrees, sin, cos
import numpy as np
from copy import deepcopy
from matplotlib.font_manager import findfont, FontProperties
try:
from picamera2 import Picamera2 # @UnresolvedImport
except ModuleNotFoundError:
pass
from PIL import Image, ImageFile, ImageDraw, ImageFont
from scipy.ndimage import zoom
import copy
import socket
import sys
import queue
from queue import Empty
from threading import Thread
import urllib.parse
from collections import deque, namedtuple
import more_itertools
import lxml.etree as ET
import traceback
import mariadb
import markdown
import utilities
import constants
from cameras import RemoteOpticalPi
from odometry import Movement
from dashed_image_draw import DashedImageDraw
import configurations
from vis_lib import get_fence_mask_surface, \
grid_intersections_camera, get_polygons_from_pc, matrices_from_quad_points, \
get_prospect_list, probe_prospect_list, render_contour_row, lores_contours
from geom_lib import annot_arrow, annot_axle, distance_to_line, diff_angles
from utilities import trace_rules, trace_command, trace_location, \
despatch_to_mower_udp, \
fetch_telemetry, \
LOCATION_CSV_HEADER, \
get_mem_stats
from diagram_lib import plot_excursion, plot_contour_entry_as_projection, \
plot_projection_img
from rules_engine import RulesEngine
import poses
import tmplt_utils
from snapshot import Snapshot, SnapshotGrowth
from virtual import vmower
from mapper import ImageMapper, DataMapper
from timesheet import Timesheet
from pxm_exceptions import * # @UnusedWildImport
from itinerary import Itinerary
from fixed_length_dict import SnapshotBuffer
from cameras import OpticalVirtual
from viewport import Viewport
from forms.morphable import Morphable
from forms.rule import RuleScope
class MowerProxy():
def __init__(self, config, socket):
self.config = config
self.udp_socket = socket
def get(self):
pose = utilities.fetch_pose(self.config, self.udp_socket)
return pose
def set(self, x_m, y_m, theta_deg, axle_track_m, velocity_full_speed_mps):
utilities.despatch_to_mower_udp(
'set_pose({}, {}, {}, {}, {:.5f})'.format(
x_m,
y_m,
theta_deg,
axle_track_m,
velocity_full_speed_mps),
self.udp_socket,
self.config['mower.ip'],
self.config['mower.port'],
await_response=True,
max_attempts=3
)
class ProxymowServer(object):
linux = (platform.system() == 'Linux')
tmp_folder_path = tempfile.gettempdir()
font_path = findfont(FontProperties(family=['sans-serif']))
LOG_MAX_BYTES = constants.LOG_MAX_BYTES
LOG_BACKUP_COUNT = constants.LOG_BACKUP_COUNT
def __init__(self, args):
self.debug = args.debug
self.log_level = logging.DEBUG if self.debug else logging.WARNING
# create formatters
log_formatter = logging.Formatter(
"%(asctime)s.%(msecs)03d %(levelname)s %(module)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
data_log_formatter = logging.Formatter()
if args.work_folder is None:
work_folder_path = Path.home()
else:
work_folder_path = Path(args.work_folder).resolve()
print('Proxymow Working Directory Path:', work_folder_path.__str__())
app_root_path = Path(__file__).parent
print('Proxymow Application Root Path:', app_root_path.__str__())
self.settings_file_path_name = (
app_root_path / 'configs' / 'settings.yml').resolve().__str__()
self.config_file_path_name = (
app_root_path / 'configs' / 'config.xml').resolve().__str__()
self.image_folder_path_name = (
work_folder_path / 'images').resolve().__str__()
# ensure folder exists
if not os.path.exists(self.image_folder_path_name):
os.makedirs(self.image_folder_path_name)
self.calib_folder_path_name = (
work_folder_path / 'calib').resolve().__str__()
# ensure folder exists
if not os.path.exists(self.calib_folder_path_name):
os.makedirs(self.calib_folder_path_name)
self.calib_img_name = (
work_folder_path / 'calib' / 'calib-{}.jpg').resolve().__str__()
self.tmplt_path_name = (
app_root_path / 'templates').resolve().__str__()
self.env = Environment(loader=FileSystemLoader(self.tmplt_path_name))
log_folder_path = (work_folder_path / 'logs').resolve()
pxm_log_file_name = ((log_folder_path / 'pxm.log').resolve()).__str__()
comms_log_file_name = (
(log_folder_path / 'comms.log').resolve()).__str__()
vision_log_file_name = (
(log_folder_path / 'vision.log').resolve()).__str__()
settings_log_file_name = (
(log_folder_path / 'settings.log').resolve()).__str__()
locator_log_file_name = (
(log_folder_path / 'locator.log').resolve()).__str__()
navigation_log_file_name = (
(log_folder_path / 'navigation.log').resolve()).__str__()
last_cmds_log_file_name = (
(log_folder_path / 'last-cmds.log').resolve()).__str__()
patterns_log_file_name = (
(log_folder_path / 'patterns.log').resolve()).__str__()
excursion_log_file_name = (
(log_folder_path / 'excursion.csv').resolve()).__str__()
contours_log_file_name = (
(log_folder_path / 'contours.dat').resolve()).__str__()
# main log
self.pxm_logger = logging.getLogger('pxm')
# create handler
log_handler = RotatingFileHandler(
pxm_log_file_name, maxBytes=self.LOG_MAX_BYTES, backupCount=self.LOG_BACKUP_COUNT)
# add formatter to handler
log_handler.setFormatter(log_formatter)
self.pxm_logger.addHandler(log_handler)
self.pxm_logger.setLevel(self.log_level)
# settings log
self.settings_log = logging.getLogger('settings')
# create handler
settings_log_handler = RotatingFileHandler(
settings_log_file_name, maxBytes=self.LOG_MAX_BYTES, backupCount=self.LOG_BACKUP_COUNT)
# add formatter to handler
settings_log_handler.setFormatter(log_formatter)
self.settings_log.addHandler(settings_log_handler)
self.settings_log.setLevel(self.log_level)
# comms log
comms_logger = logging.getLogger('comms')
# create handler
comms_log_handler = RotatingFileHandler(
comms_log_file_name, maxBytes=self.LOG_MAX_BYTES, backupCount=self.LOG_BACKUP_COUNT)
# add formatter to handler
comms_log_handler.setFormatter(log_formatter)
comms_logger.addHandler(comms_log_handler)
comms_logger.setLevel(self.log_level)
# vision log
self.vision_logger = logging.getLogger('vision')
# create handler
vision_log_handler = RotatingFileHandler(
vision_log_file_name, maxBytes=self.LOG_MAX_BYTES, backupCount=self.LOG_BACKUP_COUNT)
# add formatter to handler
vision_log_handler.setFormatter(log_formatter)
self.vision_logger.addHandler(vision_log_handler)
self.vision_logger.setLevel(self.log_level)
# locator log
locator_logger = logging.getLogger('locator')
# create handler
locator_log_handler = RotatingFileHandler(
locator_log_file_name, maxBytes=self.LOG_MAX_BYTES, backupCount=self.LOG_BACKUP_COUNT)
# add formatter to handler
locator_log_handler.setFormatter(log_formatter)
locator_logger.addHandler(locator_log_handler)
locator_logger.setLevel(self.log_level)
# navigation log
navigation_logger = logging.getLogger('navigation')
# create handler
navigation_log_handler = RotatingFileHandler(
navigation_log_file_name, maxBytes=self.LOG_MAX_BYTES, backupCount=self.LOG_BACKUP_COUNT)
# add formatter to handler
navigation_log_handler.setFormatter(log_formatter)
navigation_logger.addHandler(navigation_log_handler)
navigation_logger.setLevel(self.log_level)
# last commands log
last_cmds_logger = logging.getLogger('last-cmds')
# create handler
last_cmds_log_handler = RotatingFileHandler(
last_cmds_log_file_name, maxBytes=self.LOG_MAX_BYTES, backupCount=self.LOG_BACKUP_COUNT)
# add formatter to handler
last_cmds_log_handler.setFormatter(log_formatter)
last_cmds_logger.addHandler(last_cmds_log_handler)
last_cmds_logger.setLevel(self.log_level)
# mow patterns log
pattern_logger = logging.getLogger('mow-patterns')
# create handler
pattern_log_handler = RotatingFileHandler(
patterns_log_file_name, maxBytes=self.LOG_MAX_BYTES, backupCount=self.LOG_BACKUP_COUNT)
# add formatter to handler
pattern_log_handler.setFormatter(log_formatter)
pattern_logger.addHandler(pattern_log_handler)
pattern_logger.setLevel(self.log_level)
# excursion log
excursion_logger = logging.getLogger('excursion')
# create handler
excursion_log_handler = RotatingFileHandler(
excursion_log_file_name,
maxBytes=self.LOG_MAX_BYTES,
backupCount=self.LOG_BACKUP_COUNT
)
# add formatter to handler
excursion_log_handler.setFormatter(data_log_formatter)
excursion_logger.addHandler(excursion_log_handler)
excursion_logger.setLevel(logging.ERROR) # initially logs nothing
# contours log
contour_logger = logging.getLogger('contours')
# create handler
contour_log_handler = RotatingFileHandler(
contours_log_file_name,
maxBytes=self.LOG_MAX_BYTES * 2,
backupCount=self.LOG_BACKUP_COUNT
)
# add formatter to handler
contour_log_handler.setFormatter(data_log_formatter)
contour_logger.addHandler(contour_log_handler)
contour_logger.setLevel(logging.ERROR) # initially logs nothing
self.contours_buffer = deque([], 100)
arch_file_lst = os.listdir(self.image_folder_path_name)
num_files = len(arch_file_lst)
self.archive_image_count = (
num_files + 1) % constants.ARCHIVE_IMAGE_MAX_COUNT
self.pxm_logger.info('server initialisation started...')
self.initialise()
def initialise(self):
try:
self.log('initialise started...')
self.config = configurations.Config(
self.settings_file_path_name, self.config_file_path_name, debug=self.debug, callback=self.re_init)
self.log(str(self.config))
self.db_connection = None
self.envir = {}
self.drive = {'state': ''}
self.drive_pause = False
self.drive_step = False
self.drive_cancel = False
self.drive['path'] = None
self.reset_index = 0
self.itinerary = None
self.total_destinations = 0
self.pose = None
self.cmds = []
self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udp_socket.settimeout(4)
self.udp_socket2 = socket.socket(
socket.AF_INET, socket.SOCK_DGRAM) # Mower Proxy
self.udp_socket2.settimeout(4)
self.telemetry_updated = 0 # force immediate update
self.when_checked = 0 # force
self.telem = {}
self.cutter1_state = False
self.cutter2_state = False
self.calib_image_array_cache = {}
# create instances of picam2, one per camera
try:
if not self.debug:
os.environ["LIBCAMERA_LOG_LEVELS"] = "2"
inventory = Picamera2.global_camera_info()
self.log('Camera Inventory: ' + str(inventory))
for i, attached_camera in enumerate(inventory):
if 'i2c' in attached_camera['Id']:
# its a pi camera
self.log('Creating a Picamera Object for attached pi Camera: {} Index: {}...'.format(
attached_camera['Model'], i))
self.pipicam2 = Picamera2(i)
elif 'usb' in attached_camera['Id']:
# its a usb camera
self.log('Creating a Picamera Object for attached usb Camera: {} Index: {}...'.format(
attached_camera['Model'], i))
self.usbpicam2 = Picamera2(i)
except Exception as e:
err_line = sys.exc_info()[-1].tb_lineno
err_msg = 'Unable to init OpticalPi: ' + \
str(e) + ' on line ' + str(err_line)
err_msg += ' Picamera2 not available on Windows?'
self.log_warning(err_msg)
# initialise location properties
self.location_props = {
'not_found_count': 0
}
self.extrapolation_incidents = 0
# create unpopulated mappers
self.log('init about to create mappers...', True) # log memory
self.distort_mapper = ImageMapper(
logger=self.pxm_logger, populate=False)
self.undistort_unwarp_mapper = ImageMapper(
logger=self.pxm_logger, populate=False)
self.undistort_mapper = ImageMapper(
logger=self.pxm_logger, populate=False)
self.unwarp_mapper = ImageMapper(
logger=self.pxm_logger, populate=False)
self.data_mapper = DataMapper(
logger=self.pxm_logger, populate=False)
self.grid_data_mapper = DataMapper(
logger=self.pxm_logger, populate=False)
self.rules_engine = None
self.cached_scoring_snapshot = None
self.cached_scoring_props = {}
self.re_init(True) # re-initialise artefacts
self.snapshot_buffer = SnapshotBuffer(4)
self.motivate_pose_buffer = deque([], 4)
self.consecutive_extrapolations = 0
# PIL load truncated image files
ImageFile.LOAD_TRUNCATED_IMAGES = True
# establish the input queue
self.camera_request_queue = queue.Queue(maxsize=-1)
# establish the output queues
self.camera_locate_queue = queue.Queue(maxsize=-1)
self.camera_vision_queue = queue.Queue(maxsize=-1)
self.camera_snap_queue = queue.Queue(maxsize=-1)
self.camera_raw_queue = queue.Queue(maxsize=-1)
# create and start virtual mower thread
self.vm_thread = Thread(target=self.virtual_mower)
self.vm_thread.daemon = True
self.vm_thread.start()
sleep(2.0) # allow time for virtual mower to start
# create mower proxy
self.shared = MowerProxy(self.config, self.udp_socket2)
# create and start camera worker thread
self.camera_worker = Thread(target=self.process_image)
self.camera_worker.daemon = True
self.camera_worker.start()
# create and start governor thread
self.run_governor = True
self.governor_thread = Thread(target=self.governor)
self.governor_thread.daemon = True
self.governor_thread.start()
self.log('init - complete, governor thread running: ' +
str(self.governor_thread.is_alive()))
except Exception as e:
err_line = sys.exc_info()[-1].tb_lineno
self.log_error('Error in pxm initialisation: ' +
str(e) + ' on line ' + str(err_line))
def re_init(self, first_time=False):
'''
initialise artefacts that might need re-initialising after a configuration change
'''
try:
self.log('re_init started...')
arena_width_m = self.config['arena.width_m']
arena_length_m = self.config['arena.length_m']
img_arr_cols = self.config['optical.width']
img_arr_rows = self.config['optical.height']
display_cols = self.config['optical.display_width']
display_rows = self.config['optical.display_height']
arena_matrix = self.config['calib.arena_matrix']
img_matrix = self.config['calib.img_matrix']
strength = self.config['optical.undistort_strength']
zoom = self.config['optical.undistort_zoom']
# temporary pause for governor
self.log('re_init pausing governor...')
self.run_governor = False
sleep(2)
self.log('re_init about to clear mappers...', True) # log memory
self.distort_mapper.clear()
self.undistort_unwarp_mapper.clear()
self.undistort_mapper.clear()
self.unwarp_mapper.clear()
self.data_mapper.clear()
self.log('re_init about to garbage collect...', True) # log memory
gc.collect()
self.log('re_init about to populate mappers...', True) # log memory
self.undistort_unwarp_mapper.populate(
["transform", "unbarrel"],
display_cols,
display_rows,
matrix=img_matrix,
strength=strength,
zoom=zoom
)
self.log('re_init populated undistort unwarp mapper')
self.data_mapper.populate(
["unbarrel_inv", "transform"],
img_arr_cols,
img_arr_rows,
matrix=arena_matrix,
strength=strength,
zoom=zoom
)
self.log('re_init mappers populated', True) # log memory
if self.config['current.mower'] in self.config['mowers']:
robot_span_m = self.config['mower.target_length_m']
target_width_m = self.config['mower.target_width_m']
target_radius_m = self.config['mower.target_radius_m']
target_offset_pc = self.config['mower.target_offset_pc']
body_width_m = self.config['mower.body_width_m']
body_length_m = self.config['mower.body_length_m']
axle_track_m = self.config['mower.axle_track_m']
velocity_full_speed_mps = self.config['mower.velocity_full_speed_mps']
poses.Pose.init(
self.config,
target_width_m,
robot_span_m,
target_radius_m,
target_offset_pc,
axle_track_m,
body_width_m,
body_length_m,
arena_width_m,
arena_length_m,
img_arr_cols,
img_arr_rows,
self.data_mapper,
logging.getLogger('locator')
)
Movement.init(axle_track_m, velocity_full_speed_mps)
else:
# default
robot_span_m = 0.2 # dummy values to keep things rolling
axle_track_m = 0.15
poses.Pose.init(
self.config,
0,
robot_span_m,
0,
50,
axle_track_m,
0,
0,
arena_width_m,
arena_length_m,
img_arr_cols,
img_arr_rows,
self.data_mapper,
logging.getLogger('locator')
)
vlawn_bottom_left_ref_pc = (20, 20)
vlawn_bottom_width_pc = 60
vlawn_top_width_pc = 50
vlawn_top_inset_pc = (
vlawn_bottom_width_pc - vlawn_top_width_pc) / 2
vlawn_height_pc = 60
vlawn_top_right_pc = (vlawn_bottom_left_ref_pc[0] + vlawn_top_width_pc + vlawn_top_inset_pc, 100 - (
vlawn_bottom_left_ref_pc[1] + vlawn_height_pc))
vlawn_top_left_pc = (vlawn_bottom_left_ref_pc[0] + vlawn_top_inset_pc, 100 - (
vlawn_bottom_left_ref_pc[1] + vlawn_height_pc))
vlawn_bottom_right_pc = (
vlawn_bottom_left_ref_pc[0] + vlawn_bottom_width_pc, 100 - (vlawn_bottom_left_ref_pc[1]))
vlawn_bottom_left_pc = (
vlawn_bottom_left_ref_pc[0], 100 - (vlawn_bottom_left_ref_pc[1]))
vlawn_bollards_pc = []
if constants.DISPLAY_VIRTUAL_LAWN_BOLLARDS:
vlawn_bollards_pc = [(20, 20), (90, 90), (90, 70), (70, 90),
(70, 70), (70, 20), (20, 70), (90, 20), (20, 90)]
lawn_bounds_pc = [vlawn_bottom_left_pc, vlawn_top_left_pc,
vlawn_top_right_pc, vlawn_bottom_right_pc]
distortion = 2.0
if self.linux:
try:
from lincameras import OpticalLusb
except Exception as ce1:
err_line = sys.exc_info()[-1].tb_lineno
self.log_warning(
'No Linux USB camera Available in pxm re_init: ' + str(ce1) + ' on line ' + str(err_line))
try:
from lincameras import OpticalPi
except Exception as ce2:
err_line = sys.exc_info()[-1].tb_lineno
self.log_warning(
'No Linux RPI camera Available in pxm re_init: ' + str(ce2) + ' on line ' + str(err_line))
else:
from wincameras import OpticalWusb
if self.config['device.channel'] == 'VirtualSettings':
self.camera = OpticalVirtual(
lawn_bounds_pc,
vlawn_bollards_pc,
distortion,
self.distort_mapper,
debug=self.debug
)
elif self.config['device.channel'] == 'LusbSettings':
if self.linux:
# linux webcam
self.log('Attempting to associate USB Camera...')
self.camera = OpticalLusb(
self.usbpicam2, debug=self.debug, logger=self.vision_logger)
elif self.config['device.channel'] == 'WusbSettings':
if not self.linux:
# windows webcam
self.camera = OpticalWusb(
int(self.config['device.index']), debug=self.debug, logger=self.vision_logger)
elif self.config['device.channel'].startswith('PiSettings'):
# only create once
if self.linux:
try:
self.log('Attempting to associate RPI Camera...')
self.camera = OpticalPi(
self.pipicam2, 0, debug=self.debug, logger=self.vision_logger)
self.log('Linux RPI Camera associated')
self.camera.local_config_string = None
except Exception as e:
err_line = sys.exc_info()[-1].tb_lineno
self.log_error(
'FATAL Unable to associate Linux RPI Camera: ' + str(e) + ' on line ' + str(err_line))
else:
# No pi camera 2 in windows - supply virtual camera instead!
self.camera = OpticalVirtual(
lawn_bounds_pc,
vlawn_bollards_pc,
distortion,
self.distort_mapper,
debug=self.debug
)
elif self.config['device.channel'] == 'RemotePiSettings':
self.camera = RemoteOpticalPi(self.config['device.endpoint'])
self.log('RemoteOpticalPi Camera created')
else:
print('No Camera Selected')
raise Exception('No Camera Selected')
# strategy now based on mower/lawn combination which may change
# however, we want to preserve the last n cmds & start time...
if 'rules_engine' in vars(self) and self.rules_engine is not None:
prev_last_n_cmds = self.rules_engine.last_n_commands
prev_last_n_comp_cmds = self.rules_engine.last_n_comp_commands
prev_route_started_time = self.rules_engine.route_started_time
else:
prev_last_n_cmds = None
prev_last_n_comp_cmds = None
prev_route_started_time = -1
self.rules_engine = RulesEngine(
self.config['current.strategy'],
self.config['strategy.rules'],
self.config['strategy.terms'],
self.udp_socket,
self.data_mapper
)
if prev_last_n_cmds is not None:
self.rules_engine.last_n_commands = prev_last_n_cmds
self.rules_engine.last_n_comp_commands = prev_last_n_comp_cmds
self.rules_engine.route_started_time = prev_route_started_time
# update location props
self.location_props['not_found_count'] = 0
# scoring properties
self.score_props = {}
scaled_names = ['span', 'area']
scaled_property_names = ['lower', 'scale', 'upper', 'maxscore']
measure_names = ['isoscelicity', 'solidity', 'fitness']
meas_property_names = ['lower', 'setpoint', 'upper', 'maxscore']
for name in scaled_names:
prop_list = []
for propname in scaled_property_names:
if propname == 'scale':
# scale appropriate real-world measurement from config
scale_factor = self.config['{}.{}'.format(
name, propname)]
if name == 'span':
configured_val = self.config['mower.target_length_m']
elif name == 'area':
configured_val = self.config['mower.target_area_m2']
prop_list.append(configured_val * scale_factor)
else:
prop_list.append(
self.config['{}.{}'.format(name, propname)])
self.score_props[name] = tuple(prop_list)
for name in measure_names:
prop_list = []
for propname in meas_property_names:
prop_list.append(
self.config['{}.{}'.format(name, propname)])
self.score_props[name] = tuple(prop_list)
# fence polygons
fence_polygon_percent = self.config['lawn.fence']
self.log('re_init about to construct fence polygons, data mapper {}'.format(
self.data_mapper), True) # log memory
_outer_darkzone_polygon_m, self.outer_darkzone_polygon_px = get_polygons_from_pc(
fence_polygon_percent,
arena_width_m,
arena_length_m,
constants.DARK_ZONE_FENCE_BUFFER_PERCENT, # percentage growth factor
constants.DARK_ZONE_MIN_SEGMENT_PERCENT,
data_mapper=self.data_mapper,
logger=self.pxm_logger,
debug=False
)
self.log('outer dark zone constructed')
# fence mask full-res
self.fence_mask_img = get_fence_mask_surface(
img_arr_cols,
img_arr_rows,
self.outer_darkzone_polygon_px,
ImageFont.truetype(self.font_path, 20),
like_arr=None,
debug=False,
logger=self.pxm_logger
)
# fence mask display-res
adr = self.config['optical.analysis_display_ratio']
self.fence_mask_display_img = get_fence_mask_surface(
display_cols,
display_rows,
[p // adr for p in self.outer_darkzone_polygon_px],
ImageFont.truetype(self.font_path, 20),
like_arr=None,
debug=False,
logger=self.pxm_logger
)
self.log('fence masks constructed')
self.fence_mask_array = np.asarray(self.fence_mask_img, bool)
self.fence_mask_display_array = np.asarray(
self.fence_mask_display_img, bool)
if constants.DEBUG_SAVE_IMAGE_LEVEL > 0:
self.fence_mask_img.save(
self.tmp_folder_path + 'fence-mask.jpg')
self.fence_mask_display_img.save(
self.tmp_folder_path + 'fence-mask-display.jpg')
# create viewport for windowing
self.viewport = Viewport()
# reset last visited node?
if constants.RESET_LAST_VISITED_NODE_ON_PROFILE_CHANGE:
self.config['_current.last_visited_route_node'] = None
# restart governor
self.log('re_init un-pausing governor...')
self.run_governor = True
self.log('re_init complete')
if first_time:
print('Proxymow Server successfully started! Use CTRL-C to terminate.')
print('Point your browser at http://{}:{}'.format(socket.gethostname(), cherrypy.server.socket_port))
except Exception as e:
err_line = sys.exc_info()[-1].tb_lineno
self.log_error('Error in pxm re_init: ' +
str(e) + ' on line ' + str(err_line))
def handle_GET(self, *_args, key):
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
if key == '*':
return str(self.config)
elif key == 'keys':
return str(self.config.keys())
elif key in vars(self):
self.log('GET Dict: ' + str(key))
inst_var = vars(self)[key]
json_str = json.dumps(inst_var)
return json_str
elif key.split('.')[-1].isnumeric():
raise cherrypy.HTTPError(404)
elif key in self.config:
value = self.config[key]
if value is not None:
if isinstance(value, list):
json_str = json.dumps(value, default=lambda o: {
k: v for k, v in o.__dict__.items() if not k.startswith('_')})
return json_str
else:
return str(value)
else:
raise cherrypy.HTTPError(404)
elif '.'.join(key.split('.')[:-1]) in self.config:
key_parts = key.split('.')
coll_key = '.'.join(key_parts[:-1])
rid = key_parts[-1]
value = [o for o in self.config[coll_key]
if o.__dict__[o.__class__.pk_att_name] == rid]
if value is not None:
if isinstance(value, list):
json_str = json.dumps(value, default=lambda o: {
k: v for k, v in o.__dict__.items() if not k.startswith('_')})
return json_str
else:
return str(value)
else:
raise cherrypy.HTTPError(404)
else:
raise cherrypy.HTTPError(404)
@cherrypy.expose
def handle_POST(self, *_args, key, value):
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
self.log('POST: ' + str(key) + '=' + str(value))
if key in self.config:
try:
self.config.add(key, value)
except MissingClassException:
self.log_error('POST CMD: ' + str(key) +
' Value: ' + str(value) + ' missing class')
raise cherrypy.HTTPError(500)
except DuplicateRecordException:
self.log_error('POST CMD: ' + str(key) +
' Value: ' + str(value) + ' duplicate record')
raise cherrypy.HTTPError(404)
except CollectionNotExtensibleException:
self.log_error('POST CMD: ' + str(key) + ' Value: ' +
str(value) + ' collection not extensible')
raise cherrypy.HTTPError(500)
return key + ' => ' + value
else:
raise cherrypy.HTTPError(404)
@cherrypy.expose
def handle_PATCH(self, *_args, key, value):
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
self.log('PATCH: ' + str(key) + '=' + str(value))
resp = '-1' # assume failure
try:
key_parts = key.split('.')
coll_path = '.'.join(key_parts[0:-1]) # strip id
is_valid_key = key in self.config or coll_path in self.config
except Exception:
pass
if is_valid_key:
self.log('PATCH CMD: ' + str(key) + ' updating...')
try:
self.config.patch(key, value)
except MissingClassException:
self.log_error('PATCH CMD: ' + str(key) +
' Value: ' + str(value) + ' missing class')
raise cherrypy.HTTPError(500)
except RecordNotFoundException:
self.log_error('PATCH CMD: ' + str(key) +
' Value: ' + str(value) + ' record not found')
raise cherrypy.HTTPError(404)
except AttributeNotFoundException:
self.log_error('PATCH CMD: ' + str(key) +
' Value: ' + str(value) + ' attribute not found')
raise cherrypy.HTTPError(500)
except CollectionNotUpdatableException:
self.log_error('PATCH CMD: ' + str(key) + ' Value: ' +
str(value) + ' collection not updatable')
raise cherrypy.HTTPError(500)
except ProxymowException:
self.log_error('PATCH CMD: ' + str(key) +
' Value: ' + str(value) + ' update failed')
raise cherrypy.HTTPError(500)
except Exception:
self.log_error('PATCH CMD: ' + str(key) +
' Value: ' + str(value) + ' update error')
raise cherrypy.HTTPError(500)
self.log('PATCH CMD: ' + str(key) + ' Value Written: ' +
str(value) + ' updated successfully')
resp = key + ' => ' + value
return resp
def populate_nested_element(self, element, jdict):
# need to identify element's class
klass = Morphable.get_klass(element.tag)
for k, v in jdict.items():
if type(v) is dict:
child_elem = element.find(k)
if child_elem is not None:
self.populate_nested_element(child_elem, v)
else:
self.settings_log.debug(
'populate_nested_element: no child element ' + k)
# need to identify child element's class and siblings
child_klass = Morphable.get_klass(k)
siblings = child_klass.siblings()
self.settings_log.info(
'populate_nested_element: siblings: ' + str(siblings))
# is missing child element sibling?
for sib_class in siblings:
sib_class_name = sib_class.__name__
self.settings_log.info(
'populate_nested_element searching for class:' + sib_class_name)
sib_var_name = sib_class.variable_name()
sib_child_elem = element.find(sib_var_name)
if sib_child_elem is not None:
self.settings_log.info(
'populate_nested_element removing redundant sibling {0}'.format(sib_child_elem.tag))
element.remove(sib_child_elem)
repl_elem = ET.Element(k)
element.append(repl_elem)
self.populate_nested_element(repl_elem, v)
elif k in element.attrib:
element.set(k, str(v))
self.settings_log.info(
'populate_nested_element replacement: att={0} = {1}'.format(k, element.attrib[k]))
elif element.find(k) is not None:
# writing item that is not an attribute - must be child cdata
element.find(k).text = ET.CDATA(str(v))
self.settings_log.info(
'populate_nested_element: cdata element={0}'.format(k))
elif klass is not None and k in vars(klass()):
element.set(k, str(v))
self.settings_log.info(
'populate_nested_element creation: att={0} = {1}'.format(k, element.attrib[k]))
else:
self.settings_log.warning(
'Error in populate_nested_element: {0} is neither attribute nor child element'.format(k))
@cherrypy.expose
def handle_x_PATCH(self, *args, **kwargs):
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
self.settings_log.info('handle_x_PATCH: ' +
str(args) + '=' + str(kwargs))
resp = '-1' # assume failure
key = '/'.join(args[1:])
value = kwargs['value']
try:
element = self.config.query_xpath(key)
data_dict = json.loads(value)
self.populate_nested_element(element, data_dict)
self.settings_log.debug(ET.tostring(element, pretty_print=True))
self.settings_log.info('handle_x_PATCH xpath update complete')
resp = '1'
self.settings_log.info(
'handle_x_PATCH Full Commit Saving Config...')
self.config.schedule_save() # xml => file
self.config.parse() # reload xml => database
if self.config.callback is not None:
self.config.callback()
except MissingClassException:
self.settings_log.error(
'X PATCH CMD: ' + str(key) + ' Value: ' + str(value) + ' missing class')
raise cherrypy.HTTPError(500)
except RecordNotFoundException:
self.settings_log.error(
'X PATCH CMD: ' + str(key) + ' Value: ' + str(value) + ' record not found')
raise cherrypy.HTTPError(404)
except AttributeNotFoundException:
self.settings_log.error(
'X PATCH CMD: ' + str(key) + ' Value: ' + str(value) + ' attribute not found')
raise cherrypy.HTTPError(500)
except CollectionNotUpdatableException:
self.settings_log.error(
'X PATCH CMD: ' + str(key) + ' Value: ' + str(value) + ' collection not updatable')
raise cherrypy.HTTPError(500)
except ProxymowException:
self.settings_log.error(
'X PATCH CMD: ' + str(key) + ' Value: ' + str(value) + ' update failed')
raise cherrypy.HTTPError(500)
self.settings_log.info('X PATCH CMD: ' + str(key) +
' Value Written: ' + str(value) + ' updated successfully')
return resp
@cherrypy.expose
def handle_x_POST(self, *args, **kwargs):
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
self.settings_log.info('handle_x_POST: ' +
str(args) + '=' + str(kwargs))
resp = '-1' # assume failure
key = '/'.join(args[1:])
value = kwargs['value']
mode = kwargs['mode']
try:
if mode == 'create':
coll_node = self.config.query_xpath(key)
module_name = coll_node.attrib.get('module')
# look for a blueprint
skeleton_node = self.config.cfg_root.find(
'blueprints/{0}'.format(module_name))
elif mode == 'duplicate':
skeleton_node = self.config.query_xpath(key)
coll_node = skeleton_node.getparent()
module_name = skeleton_node.tag
class_name = module_name.title()
klass = Morphable.get_klass(module_name)
extensible_att = coll_node.attrib.get('extensible')
expandable_att = coll_node.attrib.get('expandable')
orderable_att = coll_node.attrib.get('orderable')
extensible = extensible_att is not None and extensible_att == "true"
expandable = expandable_att is not None and expandable_att == "true"
orderable = orderable_att is not None and orderable_att == "true"
# create a class object
if klass is None:
self.settings_log.debug(
'handle_x_POST Class non-existent - ' + class_name)
# raise missing entity class exception
raise MissingClassException(class_name)
else:
instance = klass.from_json_str(value)
pk_name = klass.pk_att_name
pk_val = getattr(instance, pk_name)
dupe_filter = instance.as_xpath_filter()
pre_existing_item_nodes = coll_node.xpath(dupe_filter)
self.settings_log.debug(
'handle_x_POST pre_existing_item_nodes: ' + str(pre_existing_item_nodes))
if pre_existing_item_nodes is not None and len(pre_existing_item_nodes) > 0:
# raise attempt to create duplicate exception
raise DuplicateRecordException(
'\'{0}\' Already Exists'.format(pk_val))
elif extensible:
# insert new node
if skeleton_node is not None:
new_item_node = copy.deepcopy(skeleton_node)
data_dict = json.loads(value)
self.populate_nested_element(new_item_node, data_dict)
if isinstance(pk_val, int):
# then we need the next highest
next_index = self.config.get_next_in_seq(
None, module_name, pk_name)
new_item_node.set(pk_name, str(next_index))
self.settings_log.debug(
'handle_x_POST' + str(ET.tostring(new_item_node, pretty_print=True)))
else:
if expandable:
# find all nodes beyond (only works for numeric primary keys)