1
- from threading import Thread , RLock
2
- from myDevices .utils .logger import exception , info , warn , error , debug , setDebug , logJson
3
- import myDevices .schedule as schedule
4
- from time import sleep
5
- from json import dumps , loads , JSONEncoder
6
- from myDevices .cloud .dbmanager import DbManager
7
1
from datetime import datetime
2
+ from json import JSONEncoder , dumps , loads
3
+ from sqlite3 import connect
4
+ from threading import RLock , Thread
5
+ from time import sleep
6
+
7
+ import myDevices .schedule as schedule
8
+ from myDevices .utils .logger import debug , error , exception , info , logJson , setDebug , warn
8
9
9
10
10
11
class ScheduleItemEncoder (JSONEncoder ):
@@ -96,6 +97,9 @@ def __init__(self, client, name):
96
97
97
98
client: the client running the scheduler
98
99
name: name to use for the scheduler thread"""
100
+ self .connection = connect ('/etc/myDevices/agent.db' , check_same_thread = False )
101
+ self .cursor = self .connection .cursor ()
102
+ self .cursor .execute ('CREATE TABLE IF NOT EXISTS scheduled_items (id TEXT PRIMARY KEY, data TEXT)' )
99
103
Thread .__init__ (self , name = name )
100
104
self .mutex = RLock ()
101
105
#failover cases: keep last run and next run times
@@ -104,20 +108,26 @@ def __init__(self, client, name):
104
108
self .testIndex = 0
105
109
self .client = client
106
110
self .running = False
107
- self .tablename = 'scheduled_settings'
108
111
#at the end load data
109
112
self .load_data ()
110
113
self .start ()
111
-
114
+
115
+ def __del__ (self ):
116
+ """Delete scheduler object"""
117
+ try :
118
+ self .connection .close ()
119
+ except :
120
+ exception ('Error deleting SchedulerEngine' )
121
+
112
122
def load_data (self ):
113
123
"""Load saved scheduler data from the database"""
114
124
with self .mutex :
115
- results = DbManager . Select ( self .tablename )
116
- if results :
117
- for row in results :
118
- #info('Row: ' + str(row))
119
- #for each item already present in db add call AddScheduledItem with insert false
120
- self .add_scheduled_item (loads (row [1 ]), False )
125
+ self .cursor . execute ( 'SELECT * FROM scheduled_items' )
126
+ results = self . cursor . fetchall ()
127
+ for row in results :
128
+ #info('Row: ' + str(row))
129
+ #for each item already present in db add call AddScheduledItem with insert false
130
+ self .add_scheduled_item (loads (row [1 ]), False )
121
131
return True
122
132
123
133
def add_scheduled_item (self , json_data , insert = False ):
@@ -126,7 +136,7 @@ def add_scheduled_item(self, json_data, insert = False):
126
136
json_data: JSON object representing the scheduled item to add
127
137
insert: if True add the item to the database, otherwise just add it to the running scheduler"""
128
138
debug ('' )
129
- retVal = False
139
+ result = False
130
140
try :
131
141
schedule_item = ScheduleItem (json_data )
132
142
if schedule_item .id is None :
@@ -137,23 +147,23 @@ def add_scheduled_item(self, json_data, insert = False):
137
147
if insert == True :
138
148
self .add_database_item (schedule_item .id , dumps (json_data ))
139
149
info ('Setup item: ' + str (schedule_item .to_dict ()))
140
- retVal = self .setup (schedule_item )
141
- if retVal == True :
150
+ result = self .setup (schedule_item )
151
+ if result == True :
142
152
self .schedules [schedule_item .id ] = schedule_item
143
153
else :
144
- retVal = self .update_scheduled_item (json_data )
154
+ result = self .update_scheduled_item (json_data )
145
155
except :
146
156
exception ('Error adding scheduled item' )
147
157
except :
148
- exception ('AddScheduledItem Failed ' )
149
- return retVal
158
+ exception ('AddScheduledItem failed ' )
159
+ return result
150
160
151
161
def update_scheduled_item (self , json_data ):
152
162
"""Update an existing scheduled item
153
163
154
164
json_data: JSON object representing the scheduled item to update"""
155
- debug ('' )
156
- retVal = False
165
+ debug ('Update scheduled item ' )
166
+ result = False
157
167
try :
158
168
scheduleItemNew = ScheduleItem (json_data )
159
169
with self .mutex :
@@ -162,13 +172,14 @@ def update_scheduled_item(self, json_data):
162
172
schedule .cancel_job (scheduleItemOld .job )
163
173
except KeyError :
164
174
debug ('Old schedule with id = {} not found' .format (scheduleItemNew .id ))
165
- retVal = self .setup (scheduleItemNew )
166
- if retVal == True :
175
+ result = self .setup (scheduleItemNew )
176
+ debug ('Update scheduled item result: {}' .format (result ))
177
+ if result == True :
167
178
self .update_database_item (dumps (json_data ), scheduleItemNew .id )
168
179
self .schedules [scheduleItemNew .id ] = scheduleItemNew
169
180
except :
170
- exception ('UpdateScheduledItem Failed ' )
171
- return retVal
181
+ exception ('UpdateScheduledItem failed ' )
182
+ return result
172
183
173
184
def setup (self , schedule_item ):
174
185
"""Setup a job to run a scheduled item
@@ -236,12 +247,12 @@ def process_action(self, schedule_item):
236
247
with self .mutex :
237
248
schedule .cancel_job (schedule_item .job )
238
249
239
- def remove_scheduled_item (self , removeItem ):
250
+ def remove_scheduled_item (self , remove_item ):
240
251
"""Remove an item that has been scheduled
241
252
242
- removeItem : a JSON object specifying the item to remove"""
253
+ remove_item : a JSON object specifying the item to remove"""
243
254
debug ('' )
244
- return self .remove_scheduled_item_by_id (removeItem ['id' ])
255
+ return self .remove_scheduled_item_by_id (remove_item ['id' ])
245
256
246
257
def remove_scheduled_item_by_id (self , id ):
247
258
"""Remove a scheduled item with the specified id
@@ -274,30 +285,29 @@ def remove_schedules(self):
274
285
275
286
def get_schedules (self ):
276
287
"""Return a list of all scheduled items"""
277
- jsonSchedules = []
288
+ schedules = []
278
289
try :
279
290
with self .mutex :
280
291
for schedule_item in self .schedules :
281
- jsonSchedules .append (self .schedules [schedule_item ].to_dict ())
292
+ schedules .append (self .schedules [schedule_item ].to_dict ())
282
293
except :
283
- exception ('GetSchedules Failed ' )
284
- return jsonSchedules
294
+ exception ('GetSchedules failed ' )
295
+ return schedules
285
296
286
- def update_schedules (self , json_data ):
297
+ def update_schedules (self , schedule_items ):
287
298
"""Update all scheduled items
288
299
289
- json_data: JSON containing a list of all the new items to schedule"""
300
+ schedule_items: list of all the new items to schedule"""
290
301
result = True
291
- logJson ('UpdateSchedules' + str ( json_data ), 'schedules' )
292
- info ('Updating schedules' )
302
+ logJson ('Update schedules: {}' . format ( schedule_items ) )
303
+ debug ('Updating schedules' )
293
304
try :
294
305
with self .mutex :
295
- jsonSchedules = json_data ['Schedules' ]
296
306
self .remove_schedules ()
297
- for item in jsonSchedules :
298
- self .add_scheduled_item (item [ 'Schedule' ] , True )
307
+ for item in schedule_items :
308
+ self .add_scheduled_item (item , True )
299
309
except :
300
- exception ('UpdateSchedules Failed ' )
310
+ exception ('UpdateSchedules failed ' )
301
311
result = False
302
312
return result
303
313
@@ -306,48 +316,58 @@ def update_database_item(self, json_data, id):
306
316
307
317
json_data: JSON containing the scheduled item
308
318
id: id of the scheduled item"""
309
- debug ('' )
319
+ debug ('Update database item ' )
310
320
result = True
311
321
try :
312
- setClause = 'data = ?'
313
- whereClause = 'id = ?'
314
322
with self .mutex :
315
- DbManager .Update (self .tablename , setClause , json_data , whereClause , id )
323
+ self .cursor .execute ('UPDATE scheduled_items SET data = ? WHERE id = ?' , (json_data , id ))
324
+ self .connection .commit ()
316
325
except :
326
+ exception ('Error updating database item' )
317
327
result = False
328
+ debug ('Update database item result: {}' .format (result ))
318
329
return result
319
330
320
331
def add_database_item (self , id , json_data ):
321
332
"""Add a scheduled item to the database
322
333
323
334
id: id of the scheduled item
324
335
json_data: JSON containing the scheduled item"""
325
- debug ('' )
336
+ debug ('Add database item ' )
326
337
result = False
327
338
with self .mutex :
328
- result = DbManager .Insert (self .tablename , id , json_data )
339
+ self .cursor .execute ('INSERT INTO scheduled_items VALUES (?,?)' , (id , json_data ))
340
+ self .connection .commit ()
341
+ result = self .cursor .lastrowid
342
+ debug ('Add database item result: {}' .format (result ))
329
343
return result
330
344
331
345
def remove_database_item (self , id ):
332
346
"""Remove a scheduled item from the database
333
347
334
348
id: id of the scheduled item"""
349
+ debug ('Remove database item' )
335
350
result = True
336
351
try :
337
352
with self .mutex :
338
- DbManager .Delete (self .tablename , id )
353
+ self .cursor .execute ('DELETE FROM scheduled_items WHERE id = ?' , (id ,))
354
+ self .connection .commit ()
339
355
except :
340
356
result = False
357
+ debug ('Remove database item result: {}' .format (result ))
341
358
return result
342
359
343
360
def remove_all_database_items (self ):
344
361
"""Remove all scheduled items from the database"""
345
362
result = True
363
+ debug ('Remove all database items' )
346
364
try :
347
365
with self .mutex :
348
- DbManager .DeleteAll (self .tablename )
366
+ self .cursor .execute ('DELETE FROM scheduled_items' )
367
+ self .connection .commit ()
349
368
except :
350
369
result = False
370
+ debug ('Remove all database items result: {}' .format (result ))
351
371
return result
352
372
353
373
def stop (self ):
@@ -364,7 +384,7 @@ def run(self):
364
384
with self .mutex :
365
385
schedule .run_pending ()
366
386
except :
367
- exception ("SchedulerEngine run, Unexpected error" )
387
+ exception ("SchedulerEngine run, unexpected error" )
368
388
sleep (1 )
369
389
370
390
0 commit comments